MATLAB: Read files in a specific order

dirfopenorder files

Hi, I have a series of files named with a date, for every third hour i.e. "NUM_1985_6_4_0_0.dat", "NUM_1985_6_4_3_0.dat", "NUM_1985_6_4_6_0.dat" ,….., "NUM_1985_6_4_21_0.dat",……, "NUM_1985_6_10_21_0.dat", "NUM_1985_6_11_0_0.dat". I'm using the dir command before using the fopen command. Is there any option when using the dir command to be able to list the files on a specific order. I would like to read the files by dates, however, the dir command gives me a list of files where the first one is "NUM_1985_6_10_0_0.dat" following a different logic, where the number 1 goes first in the list.
Thanks

Best Answer

Download my FEX submission natsorfiles, which was designed to fix the exact problem that you are having. Use it to simply sort the output from DIR:
D = '.'; % folder path
S = dir(fullfile(D,'*.dat'));
S = natsortfiles(S); % alphanumeric sort by filename
for k = 1:numel(S)
F = fullfile(D,S(k).name)
... import/process file F
end
Here is natsortfiles used on your example filenames:
>> C = {'NUM_1985_6_4_0_0.dat';'NUM_1985_6_4_3_0.dat';'NUM_1985_6_4_6_0.dat';'NUM_1985_6_4_21_0.dat';'NUM_1985_6_10_21_0.dat';'NUM_1985_6_11_0_0.dat'};
>> C = C(randperm(numel(C))) % "random" order
C =
NUM_1985_6_11_0_0.dat
NUM_1985_6_4_0_0.dat
NUM_1985_6_4_21_0.dat
NUM_1985_6_4_3_0.dat
NUM_1985_6_4_6_0.dat
NUM_1985_6_10_21_0.dat
>> D = natsortfiles(C) % alphanumeric sort
D =
NUM_1985_6_4_0_0.dat
NUM_1985_6_4_3_0.dat
NUM_1985_6_4_6_0.dat
NUM_1985_6_4_21_0.dat
NUM_1985_6_10_21_0.dat
NUM_1985_6_11_0_0.dat