Ascending Sort in a cell of file names

1 次查看(过去 30 天)
Dear friends,
I have a list of file names stored in a cell and I would like to sort this names. My cell variable is b:
Workspace: b < 15x1 cell>
b =
'p1-cimg.txt'
'p11-cimg.txt'
'p12-cimg.txt'
'p13-cimg.txt'
'p14-cimg.txt'
'p3-cimg.txt'
'p4-cimg.txt'
'p5-cimg.txt'
'p6-cimg.txt'
'p7-cimg.txt'
'p8-cimg.txt'
'p9-cimg.txt'
'p10-cimg.txt'
'p15-cimg.txt'
'p2-cimg.txt'
I would like perform an ascending sort and obtain:
b=
'p1-cimg.txt'
'p2-cimg.txt'
'p3-cimg.txt'
....
Anyone knows how to do that?
I tried use sort, but I got this error: >> sort(b) Error using sort Input argument must be a cell array of strings.
Thank you very much!

采纳的回答

Jos (10584)
Jos (10584) 2013-12-4
Given your b, try this:
num = cellfun(@(x) sscanf(x,'p%f-cimg.txt'),b) ;
[~,sortindex] = sort(num)
b(sortindex)

更多回答(1 个)

Andrei Bobrov
Andrei Bobrov 2013-12-4
b ={'p1-cimg.txt'
'p11-cimg.txt'
'p12-cimg.txt'
'p13-cimg.txt'
'p14-cimg.txt'
'p3-cimg.txt'
'p4-cimg.txt'
'p5-cimg.txt'
'p6-cimg.txt'
'p7-cimg.txt'
'p8-cimg.txt'
'p9-cimg.txt'
'p10-cimg.txt'
'p15-cimg.txt'
'p2-cimg.txt'};
ii = regexp(b,'(?<=p)\d*','match');
[i0,i0] = sort(str2double([ii{:}]));
out = b(i0);
  1 个评论
Henrique Amaral
Henrique Amaral 2013-12-5
Thank you Andrei! It works perfectly as well! I really appreciate your help.

请先登录,再进行评论。

类别

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