主要内容

本页采用了机器翻译。点击此处可查看英文原文。

com.mathworks.runtime.MatlabRuntime

Java 类,该类表示一个 MATLAB Runtime 实例

自 R2026a 起

描述

MatlabRuntime 类允许 Java® 应用程序通过将 MATLAB® Runtime 的实例用作运行时环境,与打包的 MATLAB 代码进行交互。

方法摘要

静态方法

startMatlab

同步启动 MATLAB Runtime 实例

startMatlabAsync

异步启动 MATLAB Runtime 实例

terminateMatlabClient

终止所有 MATLAB Runtime 实例并释放所有资源

实例方法

feval同步评估 MATLAB 函数
fevalAsync异步评估 MATLAB 函数
waitForFiguresToClose在所有 MATLAB 图形窗口关闭之前,阻止程序执行
关闭终止现有的 MATLAB Runtime 实例并释放其所有资源

方法详细信息

startMatlab

static MatlabRuntime startMatlab(String ctfFile, String... options)

static MatlabRuntime startMatlab(String ctfFile, ApplicationMode mode, String options)

描述

同步启动一个 MATLAB Runtime 实例,并使用指定的可部署存档文件(.ctf 文件)对其进行初始化。这将配置执行已打包到可部署存档中的 MATLAB 函数所需的运行时环境。

首次调用 startMatlab 用于确定应用程序模式和运行时选项。后续调用将忽略这些设置。

当使用 ApplicationMode 参数执行 startMatlab 时,运行时环境将根据指定的模式在进程内或进程外创建。

  • 如果提供了 ApplicationMode.OUT_OF_PROCESSMATLAB Runtime 将在单独的进程中启动。

  • 如果未指定 ApplicationMode,运行时将默认采用进程内模式。

参数
String ctfFile

可部署存档(.ctf 文件)的路径。可以是相对路径或绝对路径。

String... options

(可选) MATLAB Runtime 选项,例如 -nojvm 或其他启动参量。这些选项仅在首次调用 startMatlab 时生效,后续调用时将被忽略。有关详细信息,请参阅 MATLAB Runtime 启动选项

ApplicationMode mode

(可选) 用于指定如何启动 MATLAB Runtime 的枚举值。使用 ApplicationMode.IN_PROCESS 可在与 Java 应用程序相同的进程中启动运行时,或使用 ApplicationMode.OUT_OF_PROCESS 在单独的子进程中启动它。该参数仅在进程中首次调用 startMatlab 时被接受,后续调用时将被忽略。

返回

一个名为 MatlabRuntime 的实例已连接到已启动的 MATLAB Runtime

抛出
  • com.mathworks.matlab.exceptions.MatlabNotAvailableException - 如果 MATLAB Runtime 实例无法启动,或者在初始化过程中发生错误,则抛出此异常。

  • java.lang.InterruptedException - 当在启动过程中中断了启动 MATLAB Runtime 的线程时抛出。

  • java.lang.IllegalArgumentException - 当向方法提供无效参量时抛出。

  • java.lang.IllegalStateException - 当 MATLAB Runtime 处于无法启动的无效状态时抛出。

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

描述

异步启动一个 MATLAB Runtime 实例,并使用指定的可部署存档文件(.ctf 文件)对其进行初始化。这将配置执行已打包到可部署存档中的 MATLAB 函数所需的运行时环境。

首次调用 startMatlabAsync 用于确定应用程序模式和运行时选项。后续调用将忽略这些设置。

当使用 ApplicationMode 参数执行 startMatlabAsync 时,运行时环境将根据指定的模式在进程内或进程外创建。

  • 如果提供了 ApplicationMode.OUT_OF_PROCESSMATLAB Runtime 将在单独的进程中启动。

  • 如果未指定 ApplicationMode,运行时将默认采用进程内模式。

一旦启动过程开始,此方法便无法取消。

参数
String ctfFile

可部署存档(.ctf 文件)的路径。可以是相对路径或绝对路径。

String... options

(可选) MATLAB Runtime 选项,例如 -nojvm 或其他启动参量。这些选项仅在首次调用 startMatlab 时生效,后续调用时将被忽略。有关详细信息,请参阅 MATLAB Runtime 启动选项

ApplicationMode mode

(可选) 用于指定如何启动 MATLAB Runtime 的枚举值。使用 ApplicationMode.IN_PROCESS 可在与 Java 应用程序相同的进程中启动运行时,或使用 ApplicationMode.OUT_OF_PROCESS 在单独的子进程中启动它。该参数仅在进程中首次调用 startMatlabAsync 时被接受,后续调用时将被忽略。

返回

一个 Future<MatlabRuntime>,表示异步启动的待处理结果。当 MATLAB Runtime 实例完成初始化并准备就绪时,未来便已成形。

抛出
  • com.mathworks.matlab.exceptions.MatlabNotAvailableException - 如果 MATLAB Runtime 实例无法启动,或者在初始化过程中发生错误,则抛出此异常。

  • java.util.concurrent.ExecutionException - 当启动 MATLAB Runtime 的异步计算抛出异常时,由 Future.get() 抛出

  • java.lang.InterruptedException - 当等待 MATLAB Runtime 启动的线程被中断时,由 Future.get() 抛出

示例
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()

描述

同步终止所有剩余的 MATLAB Runtime 实例,并释放所有相关的 MATLAB 资源。调用此方法后,应用程序内将无法再执行任何 MATLAB 代码。

此方法通常用于显式清理资源。如果未手动调用,MATLAB Runtime 将在应用程序终止时自动关闭。

抛出

无。

示例
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)

描述

同步调用指定参量的 MATLAB 函数,并获取结果。支持控制预期输出数量 (nlhs),以及重定向标准输出和错误流。

该方法对来自 Java 应用程序的 MATLAB 代码进行评估,并根据请求的输出数量返回结果。

参数
func

MATLAB 函数的名称。

nlhs

(可选) 函数 MATLAB 返回的参量个数。如果未指定,则默认为 1

  • 如果 nlhs 大于 1,则返回类型 T 必须是 Object[]

  • 如果 nlhs 等于 1,则返回类型 T 可能是预期类型,也可能是 Object(如果未知)。

  • 如果 nlhs0,那么返回类型 T 必须是 Void?

output

(可选) Writer 用于捕获 MATLAB 函数的标准输出。如果未指定,输出将发送到终端或命令行窗口。使用 NULL_WRITER 来抑制输出。

error

(可选) Writer 用于获取 MATLAB 函数的标准误差。如果未指定,错误消息将发送到终端或命令行窗口。使用 NULL_WRITER 来抑制错误输出。

args

要传递给 MATLAB 函数的参量。

返回

MATLAB 函数的计算结果。返回类型取决于 nlhs 的值:

  • nlhs == 0Void?

  • nlhs == 1:预期类型或 Object

  • nlhs > 1: Object[]

抛出

  • com.mathworks.matlab.exceptions.UnsupportedTypeException - 当输入或输出类型不受 MATLAB Runtime 支持时抛出。

  • com.mathworks.matlab.exceptions.MatlabExecutionException - 当 MATLAB 代码执行过程中发生错误时抛出。

  • java.lang.InterruptedException - 当在启动过程中中断了启动 MATLAB Runtime 的线程时抛出。

  • java.lang.IllegalStateException - 当 MATLAB Runtime 处于无法启动的无效状态时抛出。

示例
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)

描述

异步评估一个 MATLAB 函数或脚本,并使用指定的参量,返回一个表示结果的 Future。这使得可以从 Java 应用程序中以非阻塞方式执行 MATLAB 代码。

预期输出值的数量通过 nlhs 参数指定。如果省略,则默认为 1。可以使用 Writer 对象重定向来自 MATLAB 的输出和错误流。

参数
func

MATLAB 函数的名称。

nlhs

(可选) 函数 MATLAB 返回的参量个数。如果未指定,则默认为 1

  • 如果 nlhs 大于 1,则返回类型 T 必须是 Object[]

  • 如果 nlhs 等于 1,则返回类型 T 可能是预期类型,也可能是 Object(如果未知)。

  • 如果 nlhs0,那么返回类型 T 必须是 Void?

output

(可选) Writer 用于捕获 MATLAB 函数的标准输出。如果未指定,输出将发送到终端或命令行窗口。使用 NULL_WRITER 来抑制输出。

error

(可选) Writer 用于获取 MATLAB 函数的标准误差。如果未指定,错误消息将发送到终端或命令行窗口。使用 NULL_WRITER 来抑制错误输出。

args

要传递给 MATLAB 函数的参量。

返回

一个 Future<T>,表示 MATLAB 函数求值的结果尚待确定。一旦计算完成且结果可用,未来便已成定局。

抛出
  • java.lang.IllegalStateException - 如果 MATLAB Runtime 不可用,则抛出此异常。

    在对返回的 Future 调用 get() 时,可能会抛出以下异常:

    • com.mathworks.matlab.exceptions.MatlabExecutionException - 当 MATLAB 代码执行过程中发生错误时抛出。

    • java.util.concurrent.ExecutionException - 包装在异步计算过程中抛出的异常。

    • java.lang.InterruptedException - 如果等待结果的线程被中断,则抛出此异常。

    • java.util.concurrent.TimeoutException - 如果计算未能在指定时间内完成,则由 get(timeout, unit) 抛出此异常。

示例
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()

描述

在执行过程中创建的任何 MATLAB 对象仍处于打开状态时,将阻塞调用程序的执行。此方法有助于确保 Java 应用程序暂停运行,直到用户关闭所有交互式 MATLAB 图形窗口为止。

抛出

无。

示例
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

关闭

void close()

描述

终止与该 MatlabRuntime 对象关联的当前 MATLAB Runtime 实例。这将释放该实例占用的所有资源。调用此方法后,该实例将无法再用于调用 MATLAB 函数。

MatlabRuntime 类实现了 AutoCloseable 接口,从而能够通过 Java 中的 try-with-resources 语句实现自动资源管理。使用 try-with-resources 时,运行时资源会在 try 模块结束时自动清理,因此无需显式调用 close() 方法。

抛出
  • com.mathworks.matlab.exceptions.MatlabNotAvailableException - 当 MATLAB Runtime 无法正常退出时抛出。

  • java.lang.IllegalStateException - 如果 MATLAB Runtime 不可用,则抛出此异常。

示例

显式调用 close 方法。

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

使用 try-with-resources 实现自动关闭。

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

版本历史记录

在 R2026a 中推出