MATLAB: How to open files automatically in certain order?(numbers giving me trouble)

order of opening files automatically

So, say I have these files named 1.0.txt, 1.5.txt, 2.0.txt, 2.5.txt, … 10.0.txt, 10.5.txt
I am automatically opening the files by loop and do what I have to do with the file.
However, Matlab seems to see the file order starting from the first letter.
There fore, Matlab executes the loop in the order of 1.0.txt, 1.5.txt, 10.0.txt, 10.5.txt, 2.0.txt, 2.5.txt… and so on.
I can I avoid this and make the loop go in the order of 1.0, 1.5, 2.0, 2.5, … 10.0, 10.5 ?
I am doing fprintf and the order is important for my calculation..

Best Answer

Exactly like I told you (and showed you) in your earlier question, you can use my FEX submission natsortfiles to sort the files into the order you want:
S = dir(...);
N = natsortfiles({S.name},'\d+(\.\d+)?');
for k = 1:numel(N)
N{k} % filename
val = sscanf(N{k},'%f') % numeric value
...
end
And here are your example strings:
>> X = {'1.0.txt','1.5.txt','10.0.txt','10.5.txt','2.0.txt','2.5.txt'}
X =
'1.0.txt' '1.5.txt' '10.0.txt' '10.5.txt' '2.0.txt' '2.5.txt'
>> natsortfiles(X,'\d+(\.\d+)?')
ans =
'1.0.txt' '1.5.txt' '2.0.txt' '2.5.txt' '10.0.txt' '10.5.txt'
Do you see that my code puts them into the order that you want? That is why in my last answer I told you to use natsortfiles.
EDIT If the files always contain only one decimal values, and these are always the leading characters of the filename, then this will also work:
>> X = {'1.0.txt','1.5.txt','10.0.txt','10.5.txt','2.0.txt','2.5.txt'};
>> N = cellfun(@(s)sscanf(s,'%f'),X);
>> [~,idx] = sort(N);
>> X(idx)
ans =
'1.0.txt' '1.5.txt' '2.0.txt' '2.5.txt' '10.0.txt' '10.5.txt'