How can I create cell arrays that are in sequential order?

3 views (last 30 days)
I've written this code to iterate through a series of .jpg images in a folder in order to create greyscale images of each picture. However, the folder creates cell arrays that aren't in sequential order as in (1, 2, 3, 4...). Instead, it goes 136, 137, 138, 139, 14, 140, 141, 142, 143... and so forth. How can I create cell arrays that are in sequential order?

Answers (2)

the cyclist
the cyclist on 16 May 2018
Edited: the cyclist on 16 May 2018
Instead of using num2str to create the string, use sprintf.
For example, you could ensure that the number 1 is expressed as 001, ensuring the ordering.
sprintf('%03d',1)
ans =
'001'

Stephen23
Stephen23 on 17 May 2018
Edited: Stephen23 on 7 Sep 2019
Two simple solutions:
  1. add sufficient leading zeros to all of the numbers (then a character sort will give the correct order). The tricky thing here is knowing in advance how many is sufficient... this is a fragile solution because in the future a user might easily define more images but not change how many leading zeros there are.
  2. download my FEX submission natsortfiles, which was written to solve exactly this problem. Use it simply like the examples in the help, the HTML documentation and the FEX description show. In your case you will want something like this:
D = uigetdir(...);
S = dir(fullfile(D,'*.jpg'));
C = natsortfiles({S.name});
N = numel(C);
I = cell(1,N);
for k = 1:N
F = fullfile(D,C{k});
I{k} = imread(F);
...
end
Note that it is recommended to use fullfile rather than concatenating strings together.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!