How to sort filenames that are stored by dir command

20 ビュー (過去 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 Center および File ExchangeFile Operations についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by