Main Content

Call Back intoMATLABfromJava

A Java®application designed for use inside of a MATLAB®program can call back into the MATLAB code using thegetCurrentMatlabmethod in thecom.mathworks.engine.MatlabEngineAPI. For information about using this API, seeMATLAB Engine API for Java.

For example, the code in this Java classExampleClasscreates a methodfevalExampleto call the MATLABsqrt函数。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 thefevalExamplemethod, connect to MATLAB usinggetCurrentMatlab. The application manages the data between the device and the MATLAB calculation. MATLAB users call thefevalExamplefunction 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 callfevalExamplefrom MATLAB, addExampleClassto the Java class path. This example assumes that the file is in your current folder. Create MATLAB objectjavaTestand call itsfevalExample函数。Theresultis the value returned bysqrt.

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

Note

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

See Also

|

Related Topics