Main Content

Start and Close MATLAB Session from Java

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 Synchronously

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 Asynchronously

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();
    }
}

Start Engine with Startup Options

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();
    }
}

Close MATLAB Engine Session

To end the MATLAB engine session, use one of these MatlabEngine methods:

MethodPurpose

close

If a Java process starts the MATLAB session as a default non-shared session, close() terminates MATLAB.

If the MATLAB session is a shared session, close() disconnects MATLAB from this Java process. MATLAB terminates when there are no other connections.

disconnect, disconnectAsync

Disconnect from the current MATLAB session synchronously or asynchronously.

quit, quitAsync

Force the shutdown of the current MATLAB session synchronously or asynchronously.

See Also

Related Topics