我知道,通过右键单击文件并选择“作为实时脚本打开”,可以将
.m
文件(特别是函数文件)转换为 .mlx
文件(保留代码注释和格式)。
是否也可以使用命令行生成(并保存)与实时脚本/实时函数相同的数据?
您可以使用
matlab.internal.liveeditor.openAsLiveCode
打开一串代码作为实时脚本。要从 .m 文件进行转换,您可以首先使用 fileread
从 .m 文件创建该字符串。
以下是在R2022b中测试的。
filepath = 'C:\foo\untitled.m'; % some .m file we want to convert
matlab.internal.liveeditor.openAsLiveCode(fileread(filepath)); % open as live script
保存文件有点痛苦,因为上面的打开函数不会返回新打开文档的句柄。我们可以从
matlab.desktop
类中获取活动文档,然后保存它:
activeDoc = matlab.desktop.editor.getActive(); % get the active editor (the new file)
activeDoc.saveAs( strrep(filepath,'.m','.mlx') ); % Save with same file name but .mlx
如果您想关闭新的编辑器窗口,您可以执行以下操作
activeDoc.close()
结果: