MATLAB Answers

# How to sort filenames that are stored by dir command

3 views (last 30 days)
Fatih Nurcin on 15 Jan 2020
Edited: Adam Danz on 18 Jan 2020
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

#### 0 Comments

Sign in to comment.

### Answers (2)

Image Analyst on 15 Jan 2020
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

#### 0 Comments

Sign in to comment.

Adam Danz on 15 Jan 2020
Edited: Adam Danz on 18 Jan 2020
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)

#### 0 Comments

Sign in to comment.

Sign in to answer this question.

R2019b