matlab代码格式:自动加空格、缩进等美化代码功能
matlab代码格式:自动加空格、缩进等美化代码功能
·
step1
打开matlab新建一个 .m 项目;并命名为 formatMHcode.m 。具体代码如下:
function formatMHcode
try %#ok
document = matlab.desktop.editor.getActive;
position = document.Selection;
document.Text = format(document.Text);
document.goToPositionInLine(position(1), position(2)) % 还原光标位置
document.smartIndentContents();
end
function code = format(code)
code = regexprep(code, {'(\S)[ \f\v\t]+\n', '([^\n])$'}, '$1\n');
tree = mtree(code, '-comments');
assert(isempty(tree.mtfind('Kind', 'ERR')))
% a(:) 不替换为 a( : )
colons = tree.mtfind('Kind', 'COLON');
colonPos = colons.position();
colonPos = colonPos(colons.lefttreepos == colons.righttreepos);
% 字符串、注释、数值中的符号以及一元操作符不处理
exc = tree.mtfind('Kind', 'CHARVECTOR') | tree.mtfind('Kind', 'STRING') | ...
tree.mtfind('Kind', 'DOUBLE') | tree.mtfind('Kind', 'COMMENT') | ...
tree.mtfind('Kind', 'UPLUS') | tree.mtfind('Kind', 'UMINUS');
excPos = [colonPos' ...
cell2mat(arrayfun(@colon, exc.lefttreepos, exc.righttreepos, 'un', 0)')];
[ops, code, start] = regexp(string(code), ...
'(\.(\^|\*|/|\\)|<=|>=|==|~=|&&|\|\||\+|\-|\*|\\|/|\^|\||&|<|>|=|,|;|:)', ...
'match', 'split', 'start');
idx = ~ismember(start, excPos);
code(idx) = regexprep(code(idx), '[ \f\r\t\v]+$', '');
code([false idx]) = regexprep(code([false idx]), '^[ \f\r\t\v]+', '');
ops(idx) = ops(idx) + " ";
idx = idx & ~ops.startsWith(["," ";"]);
ops(idx) = " " + ops(idx);
code = char(strjoin([code; ops ""], ''));
step2
点运行,运行并保存代码;
step3
按如下步骤操作
主页-->收藏夹-->新建收藏项-->命名标签label“代码美化”-->添加到快速访问工具栏,那两个工具栏打勾-->保存。
保存完毕后在下图中位置就会出现添加的快捷标签:
step4:
注:再点击图标后,第一次使用会出现在命令框出现“需要添加到路径”。
matlab在命令行会提示,只需要点击 “将文件夹添加到MATLAB路径” 即可。然后再次点击添加的图标即可正常使用。

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)