com.mathworks.runtime.MatlabRuntime
Java class that represents a MATLAB Runtime instance
Since R2026a
Description
The MatlabRuntime class enables Java® applications to interact with packaged MATLAB® code using an instance of MATLAB Runtime as the runtime environment.
Method Summary
Static Methods
| startMatlab | Start MATLAB Runtime instance synchronously |
| startMatlabAsync | Start MATLAB Runtime instance asynchronously |
| terminateMatlabClient | Terminate all MATLAB Runtime instances and release all resources |
Instance Methods
| feval | Evaluate MATLAB function synchronously |
| fevalAsync | Evaluate MATLAB function asynchronously |
| waitForFiguresToClose | Block program execution until all MATLAB figure windows are closed |
| close | Terminate an existing MATLAB Runtime instance and release all its resources |
Method Details
startMatlab
static MatlabRuntime startMatlab(String ctfFile, String...
options)
static MatlabRuntime startMatlab(String ctfFile, ApplicationMode mode, String
options)
Starts a MATLAB Runtime instance synchronously and initializes it with the specified deployable
archive (.ctf file). This sets up the runtime environment required to
execute MATLAB functions that have been packaged into the deployable archive.
The first call to startMatlab determines the application mode and
runtime options. Later calls ignore these settings.
When startMatlab is executed with the
ApplicationMode parameter, the runtime is created either in-process
or out-of-process depending on the specified mode.
If
ApplicationMode.OUT_OF_PROCESSis provided, MATLAB Runtime is launched in a separate process.If no
ApplicationModeis specified, the runtime defaults to in-process mode.
String ctfFile | Path to deployable archive ( |
String... options | (Optional)
MATLAB Runtime options such as |
ApplicationMode mode | (Optional) Enum value that specifies how to launch
the MATLAB Runtime. Use |
An instance of MatlabRuntime connected to the started MATLAB Runtime.
com.mathworks.matlab.exceptions.MatlabNotAvailableException— Thrown if the MATLAB Runtime instance fails to start or if an error occurs during initialization.java.lang.InterruptedException— Thrown when the thread starting MATLAB Runtime is interrupted during the startup process.java.lang.IllegalArgumentException— Thrown when invalid arguments are provided to the method.java.lang.IllegalStateException— Thrown when MATLAB Runtime is in an invalid state for starting.
public class Example {
public static void main(String[] args) {
String ctfPath = "C:/path/to/your/ctf";
try (MatlabRuntime runtime = MatlabRuntime.startMatlab(ctfPath)) {
// Execute MATLAB function
double[][] result = runtime.feval(1, "mymagic", 3);
} catch (MatlabNotAvailableException e) {
// Handle case where MATLAB Runtime is not available
System.out.println("MATLAB Runtime could not be started: " + e.getMessage());
} catch (InterruptedException e) {
System.out.println("Operation was interrupted: " + e.getMessage());
} catch (IllegalArgumentException e) {
// Missing handler for this exception
System.out.println("Invalid arguments provided: " + e.getMessage());
} catch (IllegalStateException e) {
// Missing handler for this exception
System.out.println("MATLAB Runtime is in an invalid state: " + e.getMessage());
} catch (UnsupportedTypeException e) {
// Missing handler for feval exception
System.out.println("Unsupported type in function call: " + e.getMessage());
}
}
}
ApplicationModepublic class Example {
public static void main(String[] args) {
String ctfPath = "C:/path/to/your/ctf";
try (MatlabRuntime runtime = MatlabRuntime.startMatlab(
ctfPath,
ApplicationMode.IN_PROCESS, // Explicitly set application mode
"-nojvm", // Additional startup options
"-nodisplay")) {
// Use the runtime
double[][] magicSquare = runtime.feval(1, "myfun", 3);
// Print results
for (double[] row : magicSquare) {
System.out.println(Arrays.toString(row));
}
} catch (MatlabNotAvailableException e) {
System.out.println("MATLAB Runtime could not be started: " + e.getMessage());
} catch (InterruptedException e) {
System.out.println("Operation was interrupted: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("Invalid arguments provided: " + e.getMessage());
} catch (IllegalStateException e) {
System.out.println("MATLAB Runtime is in an invalid state: " + e.getMessage());
} catch (UnsupportedTypeException e) {
System.out.println("Unsupported type in function call: " + e.getMessage());
}
}
}startMatlabAsync
static Future< MatlabRuntime > startMatlabAsync(String ctfFile, String...
options)
static Future< MatlabRuntime > startMatlabAsync(String ctfFile,
ApplicationMode mode, String... options)
Starts a MATLAB Runtime instance asynchronously and initializes it with the specified deployable
archive (.ctf file). This sets up the runtime environment required to
execute MATLAB functions that have been packaged into the deployable archive.
The first call to startMatlabAsync determines the application mode
and runtime options. Later calls ignore these settings.
When startMatlabAsync is executed with the
ApplicationMode parameter, the runtime is created either in-process
or out-of-process depending on the specified mode.
If
ApplicationMode.OUT_OF_PROCESSis provided, MATLAB Runtime is launched in a separate process.If no
ApplicationModeis specified, the runtime defaults to in-process mode.
This method cannot be cancelled once the startup process begins.
String ctfFile | Path to deployable archive ( |
String... options | (Optional)
MATLAB Runtime options such as |
ApplicationMode mode | (Optional) Enum value that specifies how to launch
the MATLAB Runtime. Use |
A Future<MatlabRuntime> representing the pending result of the
asynchronous startup. The future completes when the MATLAB Runtime instance has finished initializing and is ready for use.
com.mathworks.matlab.exceptions.MatlabNotAvailableException— Thrown if the MATLAB Runtime instance fails to start or if an error occurs during initialization.java.util.concurrent.ExecutionException— Thrown byFuture.get()when the asynchronous computation of starting MATLAB Runtime throws an exceptionjava.lang.InterruptedException— Thrown byFuture.get()when the thread waiting for MATLAB Runtime to start is interrupted
public class Example {
public static void main(String[] args) {
try {
String ctfPath = "C:/path/to/your/ctf";
// Start MATLAB Runtime asynchronously
Future<MatlabRuntime> asyncRuntime = MatlabRuntime.startMatlabAsync(ctfPath);
System.out.println("MATLAB Runtime is starting in the background...");
// Get the runtime when ready and use try-with-resources
try (MatlabRuntime runtime = asyncRuntime.get()) {
// Execute packaged MATLAB function
double[][] magicSquare = runtime.feval(1, "mymagic", 3);
// Print results
for (double[] row : magicSquare) {
System.out.println(Arrays.toString(row));
}
}
} catch (MatlabNotAvailableException e) {
System.out.println("MATLAB Runtime could not be launched: " + e.getMessage());
} catch (InterruptedException e) {
System.out.println("Operation was interrupted: " + e.getMessage());
Thread.currentThread().interrupt(); // Restore interrupted status
} catch (ExecutionException e) {
System.out.println("Error during MATLAB Runtime execution: " + e.getMessage());
} catch (UnsupportedTypeException e) {
System.out.println("Unsupported type in function call: " + e.getMessage());
}
}
}
terminateMatlabClient
static void terminateMatlabClient()
Terminates all remaining MATLAB Runtime instances synchronously and releases all associated MATLAB resources. After this method is called, no further MATLAB code can be executed within the application.
This method is typically used for explicit resource cleanup. If it is not called manually, MATLAB Runtime shuts down automatically during application termination.
None.
public class Example {
public static void main(String[] args) {
String ctfPath = "C:/path/to/your/ctf";
try (MatlabRuntime runtime = MatlabRuntime.startMatlab(ctfPath)) {
// Execute MATLAB function
double[][] magicSquare = runtime.feval(1, "mymagic", 3);
// Print results
for (double[] row : magicSquare) {
System.out.println(Arrays.toString(row));
}
// Terminate the MATLAB Runtime client infrastructure.
// After this call, no other parts of this Java application
// will be able to create new MATLAB Runtime sessions
MatlabRuntime.terminateMatlabClient();
} catch (MatlabNotAvailableException | InterruptedException | IllegalArgumentException | IllegalStateException e) {
System.out.println("Error with MATLAB Runtime: " + e.getMessage());
} catch (UnsupportedTypeException e) {
System.out.println("Unsupported type in function call: " + e.getMessage());
}
}
}
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)
Invokes a MATLAB function synchronously with the specified input arguments and retrieves the
result. Supports control over the number of expected outputs (nlhs), as
well as redirection of standard output and error streams.
This method evaluates MATLAB code from the Java application and returns the results according to the number of requested outputs.
func | Name of the MATLAB function. |
nlhs | (Optional) Number of output arguments to return
from the MATLAB function. Defaults to
|
output | (Optional)
|
error | (Optional)
|
args | Input arguments to pass to the MATLAB function. |
The result of the MATLAB function evaluation. The return type depends on the value of
nlhs:
nlhs == 0:Voidor?nlhs == 1: expected type orObjectnlhs > 1:Object[]
com.mathworks.matlab.exceptions.UnsupportedTypeException— Thrown when the input or output types are not supported by the MATLAB Runtime.com.mathworks.matlab.exceptions.MatlabExecutionException— Thrown when an error occurs during MATLAB code execution.java.lang.InterruptedException— Thrown when the thread starting MATLAB Runtime is interrupted during the startup process.java.lang.IllegalStateException— Thrown when MATLAB Runtime is in an invalid state for starting.
public class Example {
public static void main(String[] args) {
String ctfPath = "C:/path/to/your/ctf";
try (MatlabRuntime runtime = MatlabRuntime.startMatlab(ctfPath)) {
// Call MATLAB function to compute magic square
double[][] magicSquare = runtime.feval(1, "mymagic", 3);
// Print the results
for (double[] row : magicSquare) {
System.out.println(Arrays.toString(row));
}
} catch (MatlabExecutionException e) {
System.out.println("MATLAB execution error: " + e.getMessage());
} catch (MatlabNotAvailableException | InterruptedException | IllegalArgumentException | IllegalStateException e) {
System.out.println("Error with MATLAB Runtime: " + e.getMessage());
} catch (UnsupportedTypeException e) {
System.out.println("Unsupported type in function call: " + e.getMessage());
}
}
}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)
Asynchronously evaluates a MATLAB function or script with the specified input arguments and returns a
Future representing the result. This allows non-blocking execution of
MATLAB code from the Java application.
The number of expected output values is specified using the nlhs
parameter. If omitted, it defaults to 1. Output and error streams from
MATLAB can be redirected using Writer objects.
func | Name of the MATLAB function. |
nlhs | (Optional) Number of output arguments to return
from the MATLAB function. Defaults to
|
output | (Optional)
|
error | (Optional)
|
args | Input arguments to pass to the MATLAB function. |
A Future<T> representing the pending result of the MATLAB function evaluation. The future completes once the computation is finished
and the result is available.
java.lang.IllegalStateException— Thrown if MATLAB Runtime is not available.When calling
get()on the returnedFuture, these exceptions can be thrown:com.mathworks.matlab.exceptions.MatlabExecutionException— Thrown when an error occurs during MATLAB code execution.java.util.concurrent.ExecutionException— Wraps exceptions thrown during the asynchronous computation.java.lang.InterruptedException— Thrown if the thread waiting for the result is interrupted.java.util.concurrent.TimeoutException— Thrown byget(timeout, unit)if the computation doesn't complete within the specified time.
public class Example {
public static void main(String[] args) {
String ctfPath = "C:/path/to/your/ctf";
try (MatlabRuntime runtime = MatlabRuntime.startMatlab(ctfPath)) {
// Start async computation of magic square
Future<double[][]> asyncResult = runtime.fevalAsync(1, "mymagic", 3);
System.out.println("Magic square calculation started in background...");
// Do other work while calculation runs
// ...
// Get the result when ready
double[][] magicSquare = asyncResult.get();
// Print results
for (double[] row : magicSquare) {
System.out.println(Arrays.toString(row));
}
} catch (MatlabNotAvailableException | InterruptedException | IllegalArgumentException | IllegalStateException e) {
System.out.println("Error with MATLAB Runtime: " + e.getMessage());
} catch (ExecutionException e) {
System.out.println("Error during asynchronous execution: " + e.getMessage());
}
}
}waitForFiguresToClose
void waitForFiguresToClose()
Blocks execution of the calling program while any MATLAB figures created during execution remain open. This method is useful for ensuring that the Java application pauses until all interactive MATLAB figure windows are closed by the user.
None.
public class Example {
public static void main(String[] args) {
String ctfPath = "C:/path/to/your/ctf";
try (MatlabRuntime runtime = MatlabRuntime.startMatlab(ctfPath)) {
// Call MATLAB function to plot something
runtime.feval(0, "plotFunction");
System.out.println("Displaying plot. Close the figure window to continue...");
// Wait for user to close all figure windows
runtime.waitForFiguresToClose();
System.out.println("All figures closed, continuing with program...");
} catch (MatlabNotAvailableException | InterruptedException | IllegalArgumentException | IllegalStateException e) {
System.out.println("Error with MATLAB Runtime: " + e.getMessage());
} catch (UnsupportedTypeException e) {
System.out.println("Unsupported type in function call: " + e.getMessage());
}
}
}plotFunction.m
function plotFunction() x = 0:0.1:10; y = sin(x); plot(x, y); title('Simple Sine Wave'); end
close
void close()
Terminates the current MATLAB Runtime instance associated with this MatlabRuntime object. This
releases all resources held by the instance. After calling this method, the instance can
no longer be used to invoke MATLAB functions.
The MatlabRuntime class implements the AutoCloseable
interface, enabling automatic resource management through the
try-with-resources statement in Java. When using try-with-resources, the runtime resources are automatically
cleaned up at the end of the try block, eliminating the need for explicit
close() method calls.
com.mathworks.matlab.exceptions.MatlabNotAvailableException— Thrown when MATLAB Runtime fails to exit properly.java.lang.IllegalStateException— Thrown if MATLAB Runtime is not available.
Explicitly calling the close method.
public class Example {
public static void main(String[] args) {
try {
String ctfPath = "C:/path/to/your/ctf";
// Create runtime instance
MatlabRuntime runtime = MatlabRuntime.startMatlab(ctfPath);
// Use the runtime
double[][] magicSquare = runtime.feval(1, "myfun", 3);
// Print results
for (double[] row : magicSquare) {
System.out.println(Arrays.toString(row));
}
// Explicitly close the runtime instance and release resources
runtime.close();
} catch (MatlabNotAvailableException e) {
System.out.println("MATLAB Runtime could not be started or terminated: " + e.getMessage());
} catch (InterruptedException e) {
System.out.println("Operation was interrupted: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("Invalid arguments provided: " + e.getMessage());
} catch (IllegalStateException e) {
System.out.println("MATLAB Runtime is in an invalid state: " + e.getMessage());
} catch (UnsupportedTypeException e) {
System.out.println("Unsupported type in function call: " + e.getMessage());
}
}
}
Using try-with-resources for automatic closing.
public class Example {
public static void main(String[] args) {
String ctfPath = "C:/path/to/your/ctf";
try (MatlabRuntime runtime = MatlabRuntime.startMatlab(ctfPath)) {
// Use the runtime
double[][] magicSquare = runtime.feval(1, "myfun", 3);
// Print results
for (double[] row : magicSquare) {
System.out.println(Arrays.toString(row));
}
// No need to explicitly call close() - try-with-resources will handle it
} catch (MatlabNotAvailableException e) {
System.out.println("MATLAB Runtime could not be started or terminated: " + e.getMessage());
} catch (InterruptedException e) {
System.out.println("Operation was interrupted: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("Invalid arguments provided: " + e.getMessage());
} catch (IllegalStateException e) {
System.out.println("MATLAB Runtime is in an invalid state: " + e.getMessage());
} catch (UnsupportedTypeException e) {
System.out.println("Unsupported type in function call: " + e.getMessage());
}
}
}
Version History
Introduced in R2026a