Sorting files inside a folder
11 次查看(过去 30 天)
显示 更早的评论
I have files named
1 1a.bmp
1 1b.bmp
1 2a.bmp
1 2b.bmp
...
2 1a.bmp
2 1b.bmp
2 2a.bmp
2 2b.bmp
....
23 1a.bmp
23 1b. bmp
and so on
in a single folder. I have to sort these files in the order
1 1a.bmp
1 1b.bmp
2 1a.bmp
2 1b.bmp
3 1a.bmp
3 1b.bmp
...
23 1a.bmp
23 1b.bmp
1 2a.bmp
1 2b.bmp
....
23 2a.bmp
23 2b.bmp
and so on. Kindly help me with the syntax for this in Matlab.
1 个评论
Stephen23
2017-1-17
编辑:Stephen23
2017-1-17
The best solution would be to name the files so that the names could be sorted by any standard sort algorithm. That would mean placing the most significant field first, and the least significant last, and using leading zeros.
Why is this a better solution? Because fixing the problem is always better than writing hack code to try and "fix" it later.
You might like to experiment with my FEX submission:
采纳的回答
Stephen23
2017-1-17
编辑:Stephen23
2017-1-19
This code gives the order requested in the original question:
C = {...
'1 1a.bmp';...
'1 1b.bmp';...
'1 2a.bmp';...
'1 2b.bmp';...
'2 1a.bmp';...
'2 1b.bmp';...
'2 2a.bmp';...
'2 2b.bmp';...
'23 1a.bmp';...
'23 1b.bmp';...
};
%
fun = @(s)sscanf(s,'%u%u%c.bmp').';
D = cellfun(fun,C,'UniformOutput',false);
[~,idx] = sortrows(cell2mat(D),[2,1,3]);
out = C(idx)
generating this:
out =
'1 1a.bmp'
'1 1b.bmp'
'2 1a.bmp'
'2 1b.bmp'
'23 1a.bmp'
'23 1b.bmp'
'1 2a.bmp'
'1 2b.bmp'
'2 2a.bmp'
'2 2b.bmp'
更多回答(2 个)
Image Analyst
2017-1-17
1 个评论
Stephen23
2017-1-17
@Image Analyst: it is not quite a natural order sort, because the fields (characters or numbers) are not parsed from from left to right.
Andrei Bobrov
2017-1-18
My small contribution
x = regexp(C,'(\d+) (\d+)([ab])','tokens','once');
y = cat(2,x{:});
[~,ii] = sortrows([str2double(y(1:2,:));cellfun(@(x)x-'0',y(end,:))]',[2 1 3]);
out = C(ii)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!