Evaluate MATLAB Statements from Java
Evaluating MATLAB Statements
You can evaluate MATLAB® statements from Java® using the MatlabEngine
eval and evalAsync methods. These methods are
similar to the MATLAB
eval function. However, the
eval and evalAsync methods do not return
the results of evaluating the MATLAB statement.
You can also use the MatlabEngine
feval and fevalAsync methods to call
MATLAB functions. These methods enable you to pass variables to the
MATLAB workspace and return values to Java.
The input arguments named in the string must exist in the MATLAB workspace. You can assign the results of the evaluation to variables within the statement string. The variable names that you assign in the statement are created in the MATLAB base workspace. MATLAB does not require you to initialize the variables created in the expression.
To return the variables created in the MATLAB workspace, use the MatlabEngine
getVariable or getVariableAsync
methods.
Evaluate Mathematical Function in MATLAB
This example code evaluates a mathematical function over a specified domain using
two MATLAB statements. The meshgrid function creates MATLAB variables X, Y, and
Z in the MATLAB workspace. These variables are used by the mathematical expression in
the next call to evalAsync.
The MatlabEngine
getVariable method returns the result of the evaluation to
Java.
import com.mathworks.engine.*;
public class javaEvalFunc {
public static void main(String[] args) throws Exception {
MatlabEngine eng = MatlabEngine.startMatlab();
eng.evalAsync("[X, Y] = meshgrid(-2:0.2:2);");
eng.evalAsync("Z = X .* exp(-X.^2 - Y.^2);");
Object[] Z = eng.getVariable("Z");
eng.close();
}
}