Sorting files in struct according to time in filename

1 次查看(过去 30 天)
Hello,
I have jpg images with names:
t_=_15_s.jpg
t_=_30_s.jpg
...
t_=_900_s.jpg
and I read them using dir(*.jpg) command. Unfortunatelly, they are sorted wrongly (they start with t_=_105_s.jpg), and I would like to correct it.
I would like to ask you for help.
BR
Mathew
  3 个评论
Mathew Smith
Mathew Smith 2024-3-21
The cyclist: I have uploaded images with the numbers to the original question so you can try.

请先登录,再进行评论。

回答(1 个)

Stephen23
Stephen23 2024-3-21
编辑:Stephen23 2024-3-21
You could download my FEX submission NATSORTFILES():
And use it like this:
S = dir('*.jpg');
S = natsortfiles(S);
Or use sufficient leading zeros in the filenames.
  4 个评论
Voss
Voss 2024-3-21
If you can't use natsortfiles, here is an alternative:
unzip images
S = dir('*.jpg');
The original order:
{S.name}.'
ans = 22x1 cell array
{'images_105.jpg'} {'images_120.jpg'} {'images_135.jpg'} {'images_15.jpg' } {'images_150.jpg'} {'images_165.jpg'} {'images_180.jpg'} {'images_195.jpg'} {'images_210.jpg'} {'images_225.jpg'} {'images_240.jpg'} {'images_255.jpg'} {'images_270.jpg'} {'images_285.jpg'} {'images_30.jpg' } {'images_300.jpg'} {'images_315.jpg'} {'images_330.jpg'} {'images_45.jpg' } {'images_60.jpg' } {'images_75.jpg' } {'images_90.jpg' }
Sort:
[~,idx] = sort(str2double(regexp({S.name},'\d+','match','once')));
S = S(idx);
Now they are sorted:
{S.name}.'
ans = 22x1 cell array
{'images_15.jpg' } {'images_30.jpg' } {'images_45.jpg' } {'images_60.jpg' } {'images_75.jpg' } {'images_90.jpg' } {'images_105.jpg'} {'images_120.jpg'} {'images_135.jpg'} {'images_150.jpg'} {'images_165.jpg'} {'images_180.jpg'} {'images_195.jpg'} {'images_210.jpg'} {'images_225.jpg'} {'images_240.jpg'} {'images_255.jpg'} {'images_270.jpg'} {'images_285.jpg'} {'images_300.jpg'} {'images_315.jpg'} {'images_330.jpg'}
Stephen23
Stephen23 2024-3-21
"I can't install these extensions to my Matlab, but thank you for help."
MATLAB files do not need to be installed: if you can write your own file then you can use this code too.
Just unzip the ZIP-file into the current directory and use it.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by