How to invoke a MATLAB program in Java?
In order to call a MATLAB program in Java, you need to use the MATLAB Engine API. Below is a simple example code that demonstrates how to call and execute a MATLAB program in Java.
import com.mathworks.engine.*;
public class MatlabIntegration {
public static void main(String[] args) {
try {
// 启动MATLAB引擎
MatlabEngine matlab = MatlabEngine.startMatlab();
// 在MATLAB中执行一个简单的命令
matlab.eval("x = 1:10;");
matlab.eval("y = x.^2;");
// 从MATLAB中获取结果
double[] result = matlab.getVariable("y");
// 打印结果
for (double value : result) {
System.out.println(value);
}
// 关闭MATLAB引擎
matlab.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Please make sure that MATLAB is installed and the library files for the MATLAB engine are added to the Java project.