com.mathworks.engine.MatlabEngine class

Package: com.mathworks.engine

Java class using MATLAB as a computational engine

Description

The com.mathworks.engine.MatlabEngine class uses a MATLAB® process as a computational engine for Java®. This class provides an interface between the Java language and MATLAB, enabling you to evaluate MATLAB functions and expressions from Java.

Constructor Summary

The MatlabEngine class provides static methods to start MATLAB and to connect to a shared MATLAB session synchronously or asynchronously. Only these static methods can instantiate this class:

Unsupported Startup Options

The engine does not support these MATLAB startup options:

  • -h

  • -help

  • -?

  • -n

  • -e

  • -softwareopengl

  • -logfile

For information on MATLAB startup options, see Commonly Used Startup Options.

Method Summary

Static Methods

startMatlab

Start MATLAB synchronously.

startMatlabAsync

Start MATLAB asynchronously.

findMatlab

Find all available shared MATLAB sessions from a local machine synchronously.

findMatlabAsync

Find all available shared MATLAB sessions from a local machine asynchronously.

connectMatlab

Connect to a shared MATLAB session on a local machine synchronously.

connectMatlabAsync

Connect to a shared MATLAB session on a local machine asynchronously.

Member Variable

NULL_WRITER

Use a writer that ignores the contents from the MATLAB command window.

Member Functions

feval

Evaluate a MATLAB function with arguments synchronously.

fevalAsync

Evaluate a MATLAB function with arguments asynchronously.

eval

Evaluate a MATLAB expression as a string synchronously.

evalAsync

Evaluate a MATLAB expression as a string asynchronously.

getVariable

Get a variable from the MATLAB base workspace synchronously.

getVariableAsync

Get a variable from the MATLAB base workspace asynchronously.

putVariable

Put a variable into the MATLAB base workspace synchronously.

putVariableAsync

Put a variable into the MATLAB base workspace asynchronously.

disconnect

Disconnect from the current MATLAB session synchronously.

disconnectAsync

Disconnect from the current MATLAB session asynchronously.

quit

Force the shutdown of the current MATLAB session synchronously.

quitAsync

Force the shutdown of the current MATLAB session asynchronously.

close

Disconnect or terminate the current MATLAB session.

Method Details

startMatlab

static MatlabEngine startMatlab(String[] options)

static MatlabEngine startMatlab()

Description

Start MATLAB synchronously.

Parameters

String[] options

Startup options used to start MATLAB engine. You can specify multiple startup options. The engine supports all MATLAB startup options, except for the options listed in Unsupported Startup Options. For a list of options, see the platform-specific command matlab (Windows), matlab (macOS), or matlab (Linux).

Returns

Instance of MatlabEngine

Throws

com.mathworks.engine.EngineException

MATLAB fails to start.

Example
String[] options = {"-noFigureWindows", "-r", "cd H:"};
MatlabEngine eng = MatlabEngine.startMatlab(options);

startMatlabAsync

static Future<MatlabEngine> startMatlabAsync(String[] options)

static Future<MatlabEngine> startMatlabAsync()

Description

Start MATLAB asynchronously. Once MATLAB has started, then cancel is a no-op.

Parameters

String[] options

Startup options used to start MATLAB engine. You can specify multiple startup options. The engine supports all MATLAB startup options, except for the options listed in Unsupported Startup Options. For a list of options, see the platform-specific command matlab (Windows), matlab (macOS), or matlab (Linux).

Returns

Instance of Future<MatlabEngine>

Example
Future<MatlabEngine> future = MatlabEngine.startMatlabAsync();

findMatlab

static String[] findMatlab()

Description

Find all shared MATLAB sessions on the local machine synchronously.

Returns

An array of the names of all shared MATLAB sessions on the local machine, or an empty vector if there are no shared MATLAB sessions available on the local machine.

Throws

com.mathworks.engine.EngineException

If there is a failure during the search for MATLAB sessions.

Example
String[] engines = MatlabEngine.findMatlab();

findMatlabAsync

static Future<String[]> findMatlabAsync()

Description

Find all shared MATLAB sessions on local machine asynchronously.

Returns

An instance of Future<String[]>

Example
Future<String[]> future = MatlabEngine.findMatlabAsync();

connectMatlab

static MatlabEngine connectMatlab(String name)

static MatlabEngine connectMatlab()

Description

Connect to a shared MATLAB session on local machine synchronously.

  • If you specify the name of a shared MATLAB session, but the engine cannot find a session with that name, the engine throws an exception.

  • If you do not specify a name and there is no shared MATLAB session available, the engine starts a new shared MATLAB session with default options.

  • If you do not specify a name and there are shared MATLAB sessions available, the engine connects to the first available session.

Parameters

String name

Name of the shared MATLAB session. Use findMatlab to get the names of shared MATLAB sessions.

Returns

An instance of MatlabEngine

Throws

com.mathworks.engine.EngineException

MATLAB fails to start or connect.

Example
MatlabEngine engine = MatlabEngine.connectMatlab();

connectMatlabAsync

static Future<MatlabEngine> connectMatlabAsync(String name)

static Future<MatlabEngine> connectMatlabAsync

Description

Connect to a shared MATLAB session on local machine asynchronously. The behavior is the same as that of connectMatlab except the mechanism is asynchronous. Once a connection has been made to MATLAB, then cancel is a no-op.

Parameters

String name

Name of the shared MATLAB session.

Returns

An instance of Future<MatlabEngine>

Example
Future<MatlabEngine> future = MatlabEngine.connectMatlabAsync();

feval

<T> T feval(int nlhs, String func, Writer output, Writer error, Object… args)

<T> T feval(int nlhs, String func, Object… args)

<T> T feval(String func, Writer output, Writer error, Object… args)

<T> T feval(String func, Object… args)

Description

Evaluate MATLAB functions with input arguments synchronously.

Parameters

String func

Name of the MATLAB function or script to evaluate.

int nlhs

Number of expected outputs. Default is 1.

If nlhs is greater than 1, the returned type T must be <Object[]>.

If nlhs is 0, the returned type T must be <Void> or <?>.

If nlhs is 1, the returned type T can be the expected type or <Object> if the type is not known.

Writer output

Stream used to store the standard output from the MATLAB function. If you do not specify a writer, the output is written to the command window or terminal. Use NULL_WRITER to ignore the output from the MATLAB command window.

Writer error

Stream used to store the standard error from the MATLAB function. If you do not specify a writer, the output is written to the command window or terminal. Use NULL_WRITER to ignore the error message from the MATLAB command window.

Object... args

Arguments to pass to the MATLAB function.

Returns

Result of executing the MATLAB function

Throws

java.util.concurrent.CancellationException

Evaluation of a MATLAB function was canceled.

java.lang.InterruptedException

Evaluation of a MATLAB function was interrupted.

java.lang.IllegalStateException

The MATLAB session is not available.

com.mathworks.engine.MatlabExcecutionException

There is a MATLAB runtime error in the function.

com.mathworks.engine.UnsupportedTypeExeption

There is an unsupported data type.

com.mathworks.engine.MatlabSyntaxException

There is a syntax error in the MATLAB function.

Example
double result = engine.feval("sqrt", 4);

fevalAsync

<T> Future<T> fevalAsync(int nlhs, String func, Writer output, Writer error, Object… args)

<T> Future<T> fevalAsync(int nlhs, String func, Object… args)

<T> Future<T> fevalAsync(String func, Writer output, Writer error, Object… args)

<T> Future<T> fevalAsync(String func, Object… args)

Description

Evaluate MATLAB functions with input arguments asynchronously.

Parameters

String func

Name of the MATLAB function or script to evaluate.

int nlhs

Number of expected outputs. Default is 1.

If nlhs is greater than 1, the returned type T must be <Object[]>.

If nlhs is 0, the returned type T must be <Void> or <?>.

If nlhs is 1, the returned type T can be the expected type or <Object> if the type is not known.

Writer output

Stream used to store the standard output from the MATLAB function. If you do not specify a writer, the output is written to the command window or terminal. Use NULL_WRITER to ignore the output from the MATLAB command window.

Writer error

Stream used to store the standard error from the MATLAB function. If you do not specify a writer, the output is written to the command window or terminal. Use NULL_WRITER to ignore the error message from the MATLAB command window.

Object... args

Arguments to pass to the MATLAB function.

Returns

An instance of Future<T>

Throws

java.lang.IllegalStateException

The MATLAB session is not available.
Example
Future<Double> future = engine.fevalAsync("sqrt", 4);

eval

void eval(String command, Writer output, Writer error)

void eval(String command)

Description

Evaluate a MATLAB statement as a string synchronously.

Parameters

String command

MATLAB statement to evaluate.

Writer output

Stream used to store the standard output from the MATLAB statement. If you do not specify a writer, the output is written to the command window or terminal. Use NULL_WRITER to ignore the output from the MATLAB command window.

Writer error

Stream used to store the standard error from the MATLAB statement. If you do not specify a writer, the output is written to the command window or terminal. Use NULL_WRITER to ignore the error message from the MATLAB command window.

Throws

java.util.concurrent.CancellationException

Evaluation of a MATLAB function was canceled.

java.lang.InterruptedException

Evaluation of a MATLAB function was interrupted.

java.lang.IllegalStateException

The MATLAB session is not available.

com.mathworks.engine.MatlabExcecutionException

There is an error in the MATLAB statement during runtime.

com.mathworks.engine.MatlabSyntaxException

There is a syntax error in the MATLAB statement.

Example
engine.eval("result = sqrt(4)");

evalAsync

Future<Void> evalAsync(String command, Writer output, Writer error)

Future<Void> evalAsync(String command)

Description

Evaluate a MATLAB statement as a string asynchronously.

Parameters

String command

MATLAB statement to evaluate.

Writer output

Stream used to store the standard output from the MATLAB statement. If you do not specify a writer, the output is written to the command window or terminal. Use NULL_WRITER to ignore the output from the MATLAB command window.

Writer error

Stream used to store the standard error from the MATLAB statement. If you do not specify a writer, the output is written to the command window or terminal. Use NULL_WRITER to ignore the error message from the MATLAB command window.

Returns

An instance of Future<Void>

Throws

java.lang.IllegalStateException

The MATLAB session is not available.

Example
Future<Void> future = engine.evalAsync("sqrt(4)");

getVariable

<T> T getVariable(String varName)

Description

Get a variable from the MATLAB base workspace.

Parameters

String varName

Name of a variable in the MATLAB base workspace.

Returns

Variable passed from the MATLAB base workspace

Throws

java.util.concurrent.CancellationException

Evaluation of this function is canceled.

java.lang.InterruptedException

Evaluation of this function is interrupted.

java.lang.IllegalStateException

The MATLAB session is not available.

Example
double myVar = engine.getVariable("myVar");

getVariableAsync

<T> Future<T> getVariableAsync(String varName)

Description

Get a variable from the MATLAB base workspace asynchronously.

Parameters

String varName

Name of a variable in MATLAB base workspace.

Returns

An instance of Future<T>

Throws

java.lang.IllegalStateException

The MATLAB session is not available.

Example
Future<Double> future = engine.getVariableAsync("myVar");

putVariable

void putVariable(String varName, T varData)

Description

Put a variable into the MATLAB base workspace.

Parameters

String varName

Name of a variable to create in the MATLAB base workspace.

T varData

Value of the variable to create in the MATLAB base workspace.

Throws

java.util.concurrent.CancellationException

Evaluation of this function is canceled.

java.lang.InterruptedException

Evaluation of this function is interrupted.

java.lang.IllegalStateException

The MATLAB session is not available.

Example
engine.putVariable("myVar", 100);

putVariableAsync

Future<Void> putVariableAsync(String varName, T varData)

Description

Put a variable into the MATLAB base workspace asynchronously.

Parameters

String varName

Name of a variable to create in the MATLAB base workspace.

T varData

Value of the variable to create in the MATLAB base workspace.

Returns

An instance of Future<Void>

Throws

java.lang.IllegalStateException

The MATLAB session is not available.

Example
Future<Void> future = engine.putVariableAsync("myVar", 100);

disconnect

void disconnect()

Description

Disconnect from the current MATLAB session.

Throws

com.mathworks.engine.EngineException

The current MATLAB session cannot be disconnected.

Example
engine.disconnect();

disconnectAsync

Future<Void> disconnectAsync()

Description

Disconnect from the current MATLAB session.

Example
Future<Void> future = engine.disconnectAsync();

quit

void quit()

Description

Force the shutdown of the current MATLAB session.

Throws

com.mathworks.engine.EngineException

The current MATLAB session cannot be shut down.

Example
engine.quit();

quitAsync

Future<Void> quitAsync()

Description

Force the shutdown of the current MATLAB session asynchronously without waiting for termination.

Returns

An instance of Future<Void>

Example
Future<Void> future = engine.quitAsync();

close

void close()

Description

MatlabEngine provides the close() method to implement the java.lang.AutoCloseable interface for MatlabEngine objects. This close() method enables you to use a try-with-resources statement to automatically disconnect or terminate the MATLAB session at the end of the statement.

The MatlabEngine close() method disconnects or terminates the current MATLAB session, depending on the context.

  • 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.

To force the shutdown or disconnection of the current MATLAB session, explicitly call MatlabEngine.quit(), MatlabEngine.disconnect(), or their asynchronous counterparts.

Example
engine.close();

Examples

Start Engine with MATLAB Desktop

import  com.mathworks.engine.*;

public class StartMatlab {
    public static void main(String[] args) throws Exception {
        MatlabEngine eng = MatlabEngine.startMatlab("-desktop");
        ...
        eng.close();
    }
}

Evaluate Function Asynchronously

This example shows how to evaluate a MATLAB function asynchronously. The workflow is:

  • Open a MATLAB session.

  • Invoke the MATLAB sqrt function with arguments asynchronously.

  • Get the result of the MATLAB function.

  • Close the MATLAB engine.

import com.mathworks.engine.MatlabEngine

Future<MatlabEngine> engFuture = MatlabEngine.startMatlabAsync();
MatlabEngine engine = engFuture.get();
double myVar = 4;
Future<Double> future = engine.fevalAsync("sqrt", myVar);
double result = future.get();
System.out.println(result);
Introduced in R2016b