如何自动打包含依赖函数的MATLAB代码以实现便捷共享?
MATLAB 自动化收集依赖函数并打包的方法
当然有便捷的自动化方法,核心是利用MATLAB自带的代码分析工具找出所有依赖的自定义函数,再批量复制打包。以下是具体实现方案:
方法一:使用内置函数 matlab.codetools.requiredFilesAndProducts
这个函数可以精准分析指定脚本/函数的所有依赖文件(自动排除MATLAB内置函数,仅保留用户自定义代码文件),步骤如下:
实现自定义 save_fully 函数
function save_fully(zipFileName, mainScript) % 默认主脚本为当前运行的脚本,未指定则自动获取 if nargin < 2 mainScript = mfilename('fullpath'); end % 分析所有依赖文件 [requiredFiles, ~] = matlab.codetools.requiredFilesAndProducts(mainScript); % 过滤掉MATLAB系统路径下的文件,仅保留用户自定义函数 userFilesIdx = arrayfun(@(f) ~contains(f, matlabroot), requiredFiles, 'UniformOutput', true); requiredUserFiles = requiredFiles(userFilesIdx); % 创建临时目录存放文件 tempDir = tempname; mkdir(tempDir); % 复制所有依赖文件到临时目录 % 若需要保留原目录结构,取消下方两行注释并替换copyfile路径 % for i = 1:length(requiredUserFiles) % [filePath, fileName] = fileparts(requiredUserFiles(i)); % subDir = fullfile(tempDir, filePath(strfind(filePath, userpath):end)); % mkdir(subDir); % copyfile(requiredUserFiles(i), fullfile(subDir, fileName)); % end % 平级存放所有文件用下面这行 copyfile(requiredUserFiles, tempDir); % 打包成zip文件 zip(zipFileName, tempDir); % 删除临时目录 rmdir(tempDir, 's'); end
使用方式
在你的主脚本末尾直接调用:
a = 1; b = fun1(a^2); % fun1 位于MATLAB路径下的其他文件夹 c = fun2(b); % fun2 位于MATLAB路径下的其他文件夹 save_fully('my_code.zip', mfilename('fullpath'));
方法二:使用旧版函数 depfun
如果使用的是较老版本的MATLAB,depfun也能实现类似功能,示例代码:
function save_fully(zipFileName, mainScript) if nargin < 2 mainScript = mfilename('fullpath'); end % 获取依赖文件列表 depList = depfun('-toponly', mainScript); % 过滤系统路径下的文件 userDepList = depList(~cellfun(@(x) startsWith(x, matlabroot), depList)); tempDir = tempname; mkdir(tempDir); copyfile(userDepList, tempDir); zip(zipFileName, tempDir); rmdir(tempDir, 's'); end
注意事项
- 私有函数(
private文件夹下的函数)会被自动识别并包含 - 保留原目录结构可以让接收方直接按原路径运行代码,避免路径问题
- 打包前可打印
requiredUserFiles列表,手动检查是否包含不必要的文件
内容的提问来源于stack exchange,提问作者yourds
相关产品推荐
相关产品推荐

