You can start a MATLAB® session from your Java® program
synchronously or asynchronously. Use these MatlabEngine
static
methods
to start MATLAB:
MatlabEngine.startMatlab
—
Start a MATLAB session synchronously.
MatlabEngine.startMatlabAsync
—
Start a MATLAB session asynchronously.
You should always terminate the MATLAB session using one of the methods in Close MATLAB Engine Session.
Start MATLAB from Java synchronously.
import com.mathworks.engine.*; public class StartMatlab { public static void main(String[] args) throws Exception { MatlabEngine eng = MatlabEngine.startMatlab(); ... eng.close(); } }
Start MATLAB from Java asynchronously. Use the get
method
of the returned Future
object to wait for the return
of the MatlabEngine
object.
import com.mathworks.engine.*; import java.util.concurrent.Future; public class StartMatlab { public static void main(String[] args) throws Exception { Future<MatlabEngine> engFuture = MatlabEngine.startMatlabAsync(); //Do work while MATLAB engine starts ... MatlabEngine eng = engFuture.get(); ... eng.close(); } }
You can specify MATLAB startup options when you start a MATLAB session. For information on MATLAB startup options, see Commonly Used Startup Options.
The MatlabEngine.startMatlab
and MatlabEngine.startMatlabAsync
methods
accept a string array as an input.
Start the engine synchronously with MATLAB startup options.
import com.mathworks.engine.*; public class StartMatlab { String[] options = {"-noFigureWindows", "-r", "cd H:"}; public static void main(String[] args) throws Exception { MatlabEngine eng = MatlabEngine.startMatlab(options); ... eng.close(); } }
Start the engine asynchronously with MATLAB startup options.
import com.mathworks.engine.*; import java.util.concurrent.Future; public class StartMatlab { public static void main(String[] args) throws Exception { String[] options = {"-noFigureWindows", "-r", "cd H:"}; Future<MatlabEngine> engFuture = MatlabEngine.startMatlabAsync(options); ... MatlabEngine eng = engFuture.get(); ... eng.close(); } }
To end the MATLAB engine session, use one of these MatlabEngine
methods:
Method | Purpose |
---|---|
If a Java process starts the MATLAB session
as a default non-shared session, If
the MATLAB session is a shared session, | |
Disconnect from the current MATLAB session synchronously or asynchronously. | |
Force the shutdown of the current MATLAB session synchronously or asynchronously. |
com.mathworks.engine.MatlabEngine