从 MATLAB 创建独立应用程序
支持的平台:Windows®、Linux®、macOS
此示例说明了如何使用 MATLAB® Compiler™ 将一个函数进行打包,该函数用于在命令提示符下输出幻方。目标系统不需要 MATLAB 的许可副本即可运行该应用程序。
注意
该应用程序不是跨平台的,可执行文件类型取决于生成它所基于的平台。
在 MATLAB 中创建函数
在 MATLAB 中,找到要部署为独立应用程序的 MATLAB 代码。
对于此示例,使用 中的 matlabroot\extern\examples\compilermagicsquare.m 文件编译。
copyfile(fullfile(matlabroot,'extern','examples','compiler','magicsquare.m');
function m = magicsquare(n) if ischar(n) n=str2double(n); end m = magic(n); disp(m)
在 MATLAB 命令行窗口中,输入 magicsquare(5);。
输出为:
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9使用 compiler.build.standaloneApplication 创建独立应用程序
使用编程方法编译一个独立应用程序。或者,如果您想使用图形界面创建独立应用程序包,请参阅使用独立应用程序编译器创建独立应用程序。
使用
compiler.build.standaloneApplication函数编译该独立应用程序。buildResults = compiler.build.standaloneApplication("magicsquare.m");您可以使用名称-值参量在
compiler.build命令中指定其他选项。有关详细信息,请参阅compiler.build.standaloneApplication。compiler.build.Results对象buildResults包含有关编译类型、生成的文件、包含的支持包和编译选项的信息。该函数会在当前工作目录中名为
magicsquarestandaloneApplication的文件夹中生成以下文件:includedSupportPackages.txt- 列出应用程序中包含的所有支持文件的文本文件。magicsquare.exe或magicsquare- 扩展名为.exe(如果在 Windows 系统上编译)或没有扩展名(如果在 Linux 或 macOS 系统上编译)的可执行文件。run_magicsquare.sh- 设置库路径并执行应用程序的 shell 脚本文件。此文件仅在 Linux 和 macOS 系统上生成。mccExcludedFiles.log- 包含应用程序中未包含的任何工具箱函数列表的日志文件。有关不支持的函数的信息,请参阅 MATLAB Compiler 限制。readme.txt- 包含有关部署前提条件的信息以及要打包以进行部署的文件列表的文本文件。requiredMCRProducts.txt- 包含 MATLAB Runtime 运行应用程序所需产品的产品 ID 的文本文件。unresolvedSymbols.txt- 包含有关未解析符号的信息的文本文件。
注意
生成的文件不包括应用程序或 MATLAB Runtime 的安装程序。要使用
buildResults对象创建安装程序,请参阅compiler.package.installer。要使用输入参量
4从 MATLAB 中测试magicsquare,请导航到magicsquarestandaloneApplication文件夹,然后根据您的操作系统执行以下命令之一:操作系统 在 MATLAB 命令窗口中测试 Windows !magicsquare 4macOS system(['./run_magicsquare.sh ',matlabroot,' 4']);Linux !./magicsquare 4
运行独立应用程序
在系统命令提示符下,导航到包含独立可执行文件的文件夹。
根据您的操作系统,使用以下命令之一通过输入参量
5运行magicsquare:操作系统 命令 Windows magicsquare 5Linux 使用 shell 脚本:
./run_magicsquare.sh<MATLAB_RUNTIME_INSTALL_DIR>5使用可执行文件:
./magicsquare 5macOS 使用 shell 脚本:
./run_magicsquare.sh<MATLAB_RUNTIME_INSTALL_DIR>5使用可执行文件:
./magicsquare.app/Contents/macOS/magicsquare 5注意
要在 Linux 和 macOS 上不使用 shell 脚本运行应用程序,必须先将 MATLAB Runtime 添加到库路径。有关详细信息,请参阅针对部署设置 MATLAB Runtime 路径。
该应用程序会在控制台中输出一个 5×5 幻方:
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
提示
要生成不启动 Windows 命令 shell 的独立应用程序,请使用
compiler.build.standaloneWindowsApplication。要指定其他编译选项,您可以使用
mcc命令创建不包含 MATLAB Runtime 或安装程序的独立应用程序。
另请参阅
compiler.build.standaloneApplication | compiler.build.standaloneWindowsApplication | compiler.build.Results | compiler.package.installer | 独立应用程序编译器 | mcc