Main Content

Call Back into MATLAB from Java

A Java® application designed for use inside of a MATLAB® program can call back into the MATLAB code using the getCurrentMatlab method in the com.mathworks.engine.MatlabEngine API. For information about using this API, see MATLAB Engine API for Java.

For example, the code in this Java class ExampleClass creates a method fevalExample to call the MATLAB sqrt function. This method is part of a larger application which might read data from a device and then apply the MATLAB function on the data. In the fevalExample method, connect to MATLAB using getCurrentMatlab. The application manages the data between the device and the MATLAB calculation. MATLAB users call the fevalExample function to bring the data into MATLAB for further action.

import  com.mathworks.engine.*;

public class ExampleClass {
    private MatlabEngine engine;

    public double fevalExample() throws Exception {
        engine = MatlabEngine.getCurrentMatlab();
        double sqrtOut = engine.feval("sqrt", 4.0);
        engine.close();
        return sqrtOut;
    }
}

To call fevalExample from MATLAB, add ExampleClass to the Java class path. This example assumes that the file is in your current folder. Create MATLAB object javaTest and call its fevalExample function. The result is the value returned by sqrt.

javaaddpath(pwd)
javaTest = ExampleClass;
result = javaTest.fevalExample()
result = 2.0

Note

Programs using the getCurrentMatlab method are supported on the MATLAB thread only. If you call this functionality from an engine application, MATLAB displays an error.

See Also

|

Related Topics