MATLAB: Textscan doesn’t read the entire .m file

.mfilereadfprintfMATLABregexpsplitsplitlinessprintfstringtextscan

Hello everyone,
WHAT I want to do: Get all the lines of any given function (.m file) into a cellarray of strings. e.g. for the 'sum.m' file I want a cell that looks like…
[x] = magicFunction('sum.m')
x = {…
'%SUM Sum of elements.'…
'% S = SUM(X) is the sum of the elements of the vector X. If X is a matrix,'…
'% S is a row vector with the sum over each column. For N-D arrays, '…
'% SUM(X) operates along the first non-singleton dimension.'…
}
etc.
WHY I want to do it: I want to be able to store my function (I'm just using sum.m as an example) with the variables created from that function. This way any settings or tweaks I made on that run will be saved with the variable. This is important to me because I have to do a lot of trial and error when doing analysis (I study neural response properties) and I may forget what properties I set.
I run 10's of programs sometimes with 20 important settings I need to record. Sometimes changing one setting at a time and then running it. The number of combinations get big pretty fast.
the below code displays my problem. You can run it on your machine to see what I mean
funcName = 'sum.m';
fid=fopen(funcName);
C ={};
C2 = {};
for k = 1: 1000
C{k, 1} = textscan(fid,'%s',1,'delimiter','\r', 'headerlines',k-1);
C2{k, 1} = textscan(fid,'%s',1,'delimiter','\n', 'headerlines',k-1);
end
fclose(fid);
for k = 1:length(C)
if ~isempty(C{k}{:})
disp(k)
end
disp(C{k}{:});
end
fprintf('\n\n\n\n')
for k = 1:length(C2)
if ~isempty(C2{k}{:})
disp(k)
end
disp(C2{k}{:});
end
edit(funcName)
I think that the "%S" in the "%SUM" in the beginning of sum.m is likely screwing me up because it is a string command??

Best Answer

You can use fileread() and splitlines().
However due to old habits I am more likely to use regexp() with the 'split' option than I am to use splitlines ()