How to read files from sub folders in sorted order?

조회 수: 13 (최근 30일)
Parthiban C
Parthiban C 2018년 8월 10일
댓글: Stephen23 2022년 1월 19일
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?
  댓글 수: 2
kondepati sudhir kumar
kondepati sudhir kumar 2019년 11월 7일
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);
Stephen23
Stephen23 2022년 1월 19일
편집: Stephen23 2022년 1월 19일
"the answer by konard and stephen is good but if you sort by time does'nt give good results..."
My answer doesn't just sort by "Time", but sorts by the entire content of the foldernames, incuding the number values.

댓글을 달려면 로그인하십시오.

답변 (2개)

Konrad
Konrad 2018년 8월 10일
편집: Konrad 2018년 8월 10일
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

Stephen23
Stephen23 2018년 8월 10일
편집: Stephen23 2022년 1월 19일
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. Note that
  • because the numbers include decimal values you will need to specify the regular expression.
  • because you are sorting foldernames you will need to specify the 'noext' option.
D = 'path where subfolders are';
S = dir(fullfile(D,'Time_*'));
S = natsortfiles(S([S.isdir]),'\d+\.?\d*','noext')
  댓글 수: 1
Stephen23
Stephen23 2022년 1월 19일
Example using a cell array:
C = {'Time_0', 'Time_1.5', 'Time_9.5', 'Time_1', 'Time_10', 'Time_2.5'};
D = natsortfiles(C,'\d+\.?\d*','noext')
D = 1×6 cell array
{'Time_0'} {'Time_1'} {'Time_1.5'} {'Time_2.5'} {'Time_9.5'} {'Time_10'}

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by