How to sort filenames that are stored by dir command

조회 수: 18 (최근 30일)
Fatih Nurcin
Fatih Nurcin 2020년 1월 15일
편집: Adam Danz 2020년 1월 18일
list = dir('*.bmp');
%preallocate cell array
img = cell(length(list),1);
f = cell(length(list), 250-100);
for i = 1:length(list)
img{i} = imread(list(i).name);
end
%Loop through each image
for i = 1:length(list)
a=img{i}
b=rgb2gray(a);
imwrite(b,sprintf('%d.png',i))
end
That is the simplified code
Problem is that
"dir" command read files in false order, for example:
file1, file11, file111, file2, file22, file222, file3, file33, file333
in fact it should be
file 1, file 2, file 3, file 11, file 22, file 33, file 111, file 222, file 333
How can sort this order in correct version

답변 (2개)

Image Analyst
Image Analyst 2020년 1월 15일
It's best if you can create the filenames with leading zeros, if you can.
If you are stuck with those names, see this link on natural sorting

Adam Danz
Adam Danz 2020년 1월 15일
편집: Adam Danz 2020년 1월 18일
This uses regular expressions to extract the file number in the pattern file###.
If that pattern is not found, the file number assigned is 0.
The vector of file numbers is sorted and the sort index can be used to sort the list of file names.
% Get directory info and list filenames in cell array
d = dir(directory);
names = {d.name}';
% Example of what names might look like
% names = {'.'; '..'; 'file1'; 'file11'; 'file111'; 'file2'; 'file22'; 'file222'; 'junk'; 'file'};
% search for pattern file# and extract the # part
[~,tokens] = regexp(names,'file(\d+)','match','tokens');
tokenValues = [tokens{:}]; %there's a shortcut for this but I can't recall it.
tokenValues = str2double([tokenValues{:}]);
fileNum = zeros(size(tokens));
fileNum(~cellfun(@isempty,tokens)) = tokenValues;
% compute the sort index of the file numbers
[~, sortIdx] = sort(fileNum);
% now you can use the sortIdx to change the order
% of the directory structure array or the file names etc.
d(sortIdx)
names(sortIdx)

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by