问题描述
我继承了一些代码,使作者厌恶分号.是否可以一劳永逸地修复所有mlint消息(至少是所有具有自动修复功能的消息),而不必单击每个消息并按ALT + ENTER?
I've inherited some code where the author had an aversion to semicolons. Is it possible to fix all the mlint messages in one go (at least all the ones with an automatic fix), rather than having to click each one and press ALT+ENTER?
推荐答案
注意:该答案使用功能 MLINT ,在较新的MATLAB版本中不再推荐使用.首选更新的功能 CHECKCODE ,下面的代码仍然可以使用只需将对MLINT的调用替换为对此较新函数的调用即可.
NOTE: This answer uses the function MLINT, which is no longer recommended in newer versions of MATLAB. The newer function CHECKCODE is preferred, and the code below will still work by simply replacing the call to MLINT with a call to this newer function.
我不知道一般基于 MLINT 消息.但是,在您的 specific 案例中,您可以采用一种自动方式将分号添加到抛出 MLINT 警告.
I don't know of a way in general to automatically fix code based on MLINT messages. However, in your specific case there is an automated way for you to add semicolons to lines that throw an MLINT warning.
首先,让我们从示例脚本junk.m
开始:
First, let's start with this sample script junk.m
:
a = 1
b = 2;
c = 'a'
d = [1 2 3]
e = 'hello';
第一,第三和第四行将为您提供 MLINT 警告消息用分号终止语句以禁止输出(在脚本内).".使用 MLINT 的功能形式,我们可以在发生此警告的文件.然后,我们可以从文件中读取所有代码行,在发生警告的行末尾添加分号,然后将代码行写回到文件中.这是执行此操作的代码:
The first, third, and fourth lines will give you the MLINT warning message "Terminate statement with semicolon to suppress output (within a script).". Using the functional form of MLINT, we can find the lines in the file where this warning occurs. Then, we can read all the lines of code from the file, add a semicolon to the ends of the lines where the warning occurs, and write the lines of code back to the file. Here's the code to do so:
%# Find the lines where a given mlint warning occurs:
fileName = 'junk.m';
mlintID = 'NOPTS'; %# The ID of the warning
mlintData = mlint(fileName,'-id'); %# Run mlint on the file
index = strcmp({mlintData.id},mlintID); %# Find occurrences of the warnings...
lineNumbers = [mlintData(index).line]; %# ... and their line numbers
%# Read the lines of code from the file:
fid = fopen(fileName,'rt');
linesOfCode = textscan(fid,'%s','Delimiter',char(10)); %# Read each line
fclose(fid);
%# Modify the lines of code:
linesOfCode = linesOfCode{1}; %# Remove the outer cell array encapsulation
linesOfCode(lineNumbers) = strcat(linesOfCode(lineNumbers),';'); %# Add ';'
%# Write the lines of code back to the file:
fid = fopen(fileName,'wt');
fprintf(fid,'%s\n',linesOfCode{1:end-1}); %# Write all but the last line
fprintf(fid,'%s',linesOfCode{end}); %# Write the last line
fclose(fid);
现在文件junk.m
应该在每行末尾都有分号.如果需要,可以将上面的代码放在一个函数中,以便可以轻松地在继承的代码的每个文件上运行它.
And now the file junk.m
should have semicolons at the end of every line. If you want, you can put the above code in a function so that you can easily run it on every file of your inherited code.
这篇关于有没有办法一次修复所有MATLAB mlint消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!