MATLAB Answers

How to read files from sub folders in sorted order?

11 views (last 30 days)
Parthiban C
Parthiban C on 10 Aug 2018
Sub folder names are something like this. Time_0, Time_0.5, Time_1, Time_2, Time_10. The file name in all the sub folders are same. Matlab sort these folder names in the order Time_0, Time_0.5, Time_1, Time_10, Time_2. But I want the files to be loaded from smallest to largest time. Someone Please help me with this?

  1 Comment

kondepati sudhir kumar
kondepati sudhir kumar on 7 Nov 2019
the answer by konard and stephen is good but if you sort by time does'nt give good results then you can use this code
d = dir('Time*');
for i=1:length(d)
folder(i,1)=string(d(i).name);
end
t_char = regexp(folder,'\_','split');
ar= str2double(ar);
[~,idx] = sort(ar);
folder = folder(idx);

Sign in to comment.

Answers (2)

Konrad
Konrad on 10 Aug 2018
Edited: Konrad on 10 Aug 2018
Hi, one solution would be to convert the time suffix to numeric and sort the numbers:
d = dir('Time*');
n = {d.name};
t_char = regexp(n,'\-?[\d\.]+$','match','once');
t_num = str2double(t_char);
[~,idx] = sort(t_num);
d_sort = d(idx);
Hope this helps. Best, Konrad

  0 Comments

Sign in to comment.


Stephen Cobeldick
Stephen Cobeldick on 10 Aug 2018
Edited: Stephen Cobeldick on 10 Aug 2018
The simplest solution is to download my FEX submission natsortfiles, which was written to solve exactly the problem that you are having:
There are plenty of examples in the Mfile help, the online documentation, and also in the HTML examples, so you won't have any problem using it. In your case, because the numbers include decimal values, you will need to specify the regular expression too, something like this:
D = 'path where subfolders are';
S = dir(fullfile(D,'Time_*'));
N = natsortfiles({S([S.isdir]).name},'\d+\.?\d*')

  0 Comments

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by