从 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的文件夹中生成文件。有关生成的文件的信息,请参阅 打包 MATLAB 函数后生成的文件。注意
生成的文件不包括应用程序或 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