主要内容

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

fevalEvaluate MATLAB function synchronously
fevalAsyncEvaluate MATLAB function asynchronously
waitForFiguresToCloseBlock program execution until all MATLAB figure windows are closed
closeTerminate 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)

Description

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_PROCESS is provided, MATLAB Runtime is launched in a separate process.

  • If no ApplicationMode is specified, the runtime defaults to in-process mode.

Parameters
String ctfFile

Path to deployable archive (.ctf file). Can be a relative or fully-qualified path.

String... options

(Optional) MATLAB Runtime options such as -nojvm or other startup arguments. These options are applied only during the first call to startMatlab and ignored during subsequent calls. For details, see MATLAB Runtime Startup Options.

ApplicationMode mode

(Optional) Enum value that specifies how to launch the MATLAB Runtime. Use ApplicationMode.IN_PROCESS to start the runtime in the same process as the Java application, or ApplicationMode.OUT_OF_PROCESS to start it in a separate child process. This parameter is accepted the first time startMatlab is called within the process and ignored during subsequent calls.

Returns

An instance of MatlabRuntime connected to the started MATLAB Runtime.

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

Example
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());
        }
    }
}
Example With ApplicationMode
public 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)

Description

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_PROCESS is provided, MATLAB Runtime is launched in a separate process.

  • If no ApplicationMode is specified, the runtime defaults to in-process mode.

This method cannot be cancelled once the startup process begins.

Parameters
String ctfFile

Path to deployable archive (.ctf file). Can be a relative or fully -qualified path.

String... options

(Optional) MATLAB Runtime options such as -nojvm or other startup arguments. These options are applied only during the first call to startMatlab and ignored during subsequent calls. For details, see MATLAB Runtime Startup Options.

ApplicationMode mode

(Optional) Enum value that specifies how to launch the MATLAB Runtime. Use ApplicationMode.IN_PROCESS to start the runtime in the same process as the Java application, or ApplicationMode.OUT_OF_PROCESS to start it in a separate child process. This parameter is accepted the first time startMatlabAsync is called within the process and ignored during subsequent calls.

Returns

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.

Throws
  • 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 by Future.get() when the asynchronous computation of starting MATLAB Runtime throws an exception

  • java.lang.InterruptedException — Thrown by Future.get() when the thread waiting for MATLAB Runtime to start is interrupted

Example
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()

Description

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.

Throws

None.

Example
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)

Description

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.

Parameters
func

Name of the MATLAB function.

nlhs

(Optional) Number of output arguments to return from the MATLAB function. Defaults to 1 if not specified.

  • If nlhs is greater than 1, the return type T must be Object[].

  • If nlhs is 1, the return type T can be the expected type or Object if unknown.

  • If nlhs is 0, the return type T must be Void or ?.

output

(Optional) Writer to capture standard output from the MATLAB function. If not provided, output is sent to the terminal or command window. Use NULL_WRITER to suppress output.

error

(Optional) Writer to capture standard error from the MATLAB function. If not provided, error messages are sent to the terminal or command window. Use NULL_WRITER to suppress error output.

args

Input arguments to pass to the MATLAB function.

Returns

The result of the MATLAB function evaluation. The return type depends on the value of nlhs:

  • nlhs == 0: Void or ?

  • nlhs == 1: expected type or Object

  • nlhs > 1: Object[]

Throws

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

Example
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)

Description

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.

Parameters
func

Name of the MATLAB function.

nlhs

(Optional) Number of output arguments to return from the MATLAB function. Defaults to 1 if not specified.

  • If nlhs is greater than 1, the return type T must be Object[].

  • If nlhs is 1, the return type T can be the expected type or Object if unknown.

  • If nlhs is 0, the return type T must be Void or ?.

output

(Optional) Writer to capture standard output from the MATLAB function. If not provided, output is sent to the terminal or command window. Use NULL_WRITER to suppress output.

error

(Optional) Writer to capture standard error from the MATLAB function. If not provided, error messages are sent to the terminal or command window. Use NULL_WRITER to suppress error output.

args

Input arguments to pass to the MATLAB function.

Returns

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.

Throws
  • java.lang.IllegalStateException — Thrown if MATLAB Runtime is not available.

    When calling get() on the returned Future, 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 by get(timeout, unit) if the computation doesn't complete within the specified time.

Example
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()

Description

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.

Throws

None.

Example
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()

Description

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.

Throws
  • com.mathworks.matlab.exceptions.MatlabNotAvailableException — Thrown when MATLAB Runtime fails to exit properly.

  • java.lang.IllegalStateException — Thrown if MATLAB Runtime is not available.

Example

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