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

blankcommentcountlineMATLAB

Is there a way to count the number of lines in a MATLAB script or function, but not count blank and comment lines?

Best Answer

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).