I would like to read some text files which are in one folder in MATLAB, count the number of lines in each file and finally sum up these numbers. I would be thankful if somebody guide me how to do it in MATLAB?
解决方案
Matlab is really not suited for that. The underlying OS usually is much better at that, so, use a system call.
Rephrasing my original answer from this question (I've learned a few new tricks since then :)
if (isunix) %# Linux, mac
[~, result] = system('wc -l *');
numLines = cellfun(@str2double, regexp(result, '([0-9]+) total', 'tokens'))
elseif (ispc) %# Windows
[~, result] = system('find /v /c "&*fake&*" *.*');
numLines = sum(str2double( regexp(result, '[0-9]+', 'match') ))
else %# Some smaller OS
error('Unsupported operating system.');
end
Note that this will work fine, except
if you're on Linux/max and have a file called total in the current directory :)
the Windows version sometimes miscounts some files by 1 or 2 lines, I don't know why...
I'm pretty sure there is a cleaner one-line-solution to parse the linux result string; the current mess is due to regexp(..., 'tokens') returning a cell of cells which is pretty inconvenient for the current context (to be honest, I haven't found many contexts where it was convenient yet), so this must be worked-around by cellfun.
But oh well, it reckon it should do the trick in most circumstances.