Count numer of lines in a MATLAB script, ignoring comments and blanks

8 vues (au cours des 30 derniers jours)
Jeffrey Snively
Jeffrey Snively le 6 Mai 2019
Commenté : Adam Danz le 6 Mai 2019
Is there a way to count the number of lines in a MATLAB script or function, but not count blank and comment lines?
  1 commentaire
Walter Roberson
Walter Roberson le 6 Mai 2019
There is no supplied way to do this.
If you do this yourself you need to watch out for %{ %} multi line comments
Fortunately matlab does not permit literals to be split between lines so you do not need to worry about ... sequences potentially hiding the fact that a line starting with a % might hypothetically be part of a string rather than a comment.

Connectez-vous pour commenter.

Réponse acceptée

Adam Danz
Adam Danz le 6 Mai 2019
Modifié(e) : Adam Danz le 6 Mai 2019
Try this out. After reading the entire file, separated by line, it removes any leading white space, then gets rid of empty lines, then gets rid of lines that start with %. Finally, it counts the number of lines left over. View "fileStr" to see what's being counted.
file = 'myfile.m'; % name file to read
fileChar = fileread(file); % read file (char)
fileStr = strtrim(regexp(fileChar, '\n', 'split'))'; % split lines, remove leading while space
% Remove empty lines
fileStr(cellfun(@isempty, fileStr)) = [];
% Detect contiguous comments
startIdx = cumsum(cellfun(@(x)strcmp(x,'%{'), fileStr));
stopIdx = cumsum(cellfun(@(x)strcmp(x,'%}'), fileStr) & startIdx>0);
contigIdx = (startIdx - stopIdx) > 0;
fileStr(contigIdx) = [];
% Remove lines that are comments
fileStr(cellfun(@(x)strcmp(x(1),'%'), fileStr)) = [];
% Count number of lines left
nLines = length(fileStr);
I tested it on a number of files and looks OK.
Updated: 4 lines in the middle added to deal with contigious comments (good catch, Walter).
  3 commentaires
Adam Danz
Adam Danz le 6 Mai 2019
Ah.... I've never used those and therefore overlook that possibility. I'll have to edit my answer.
Adam Danz
Adam Danz le 6 Mai 2019
@ Jeffrey Snively, make sure you get the most up to date version. I tried to break it lots of ways to iron out the kinks. If I make any more changes going forward I'll add a comment here to explain what they were.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Historical Contests dans Help Center et File Exchange

Produits


Version

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by