Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I prefer to abuse <a href="http://www.mathworks.se/help/matlab/ref/checkcode.html" rel="nofollow">checkcode</a> (the replacement for old <a href="http://www.mathworks.se/help/matlab/ref/mlint.html" rel="nofollow">mlint</a>) to do the parsing. Here is a suggestion </p> <pre><code>function strNC = removeComments(str) if iscell(str) strNC = cellfun(@removeComments, str, 'UniformOutput', false); elseif regexp(str, '%', 'once') err = getCheckCodeId(str); strNC = regexprep(str, '%[^%]*$', ''); errNC = getCheckCodeId(strNC); if strcmp(err, errNC), strNC = removeComments(strNC); else strNC = str; end else strNC = str; end end function errid = getCheckCodeId(line) fName = 'someTempFileName.m'; fh = fopen(fName, 'w'); fprintf(fh, '%s\n', line); fclose(fh); if exist('checkcode') structRep = checkcode(fName, '-id'); else structRep = mlint(fName, '-id'); end delete(fName); if isempty(structRep) errid = ''; else errid = structRep.id; end end </code></pre> <p>For each line, it checks if we introduce an error by trimming the line from last <code>%</code> to the end of line. </p> <p>For your example it returns:</p> <pre><code>&gt;&gt; removeComments(str) ans = 'myFun( {'test' '%'}); ' 'sprintf(str, '%*8.0f%*s%c%3d\n'); ' 'sprintf(str, '%*8.0f%*s%c%3d\n'); ' 'sprintf(str, '%*8.0f%*s%c%3d\n'); ' 'A = A.';' </code></pre> <p>It does not remove the suppression directive, <code>%#ok</code>, so you get:</p> <pre><code>&gt;&gt; removeComments('a=1; %#ok') ans = a=1; %#ok </code></pre> <p>Which probably is a good thing.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload