MATLAB: Looping to read image

imread loopingnatsortnatsortfilesnatural order sortsort_natsortnat

I have problem, i want looping to read image in order. Result that i want eg. 1. jpg, 2.jpg, 3.jpg, 4.jpg, 5.jpg, 6.jpg, 7.jpg, 8.jpg, 9.jpg, 10.jpg, 11.jpg, 12.jpg. But, the result that i get 1. jpg, 10.jpg, 11.jpg, 12.jpg, 2.jpg, 3.jpg, 4.jpg, 5.jpg, 6.jpg, 7.jpg, 8.jpg, 9.jpg I use code
hasil = dir(*jpg);
for d=1: length(hasil)
a = imread('%d.jpg', d);
end

Best Answer

My File Exchange submission natsortfiles was written exactly for solving this problem:
It sorts a cell array of strings into the order that you require, by considering all numeric values in the strings instead of just the naive character order (like sort does). You can use it very simply:
>> B = {'test2.m'; 'test10-old.m'; 'test.m'; 'test10.m'; 'test1.m'};
>> natsortfiles(B)
ans =
'test.m'
'test1.m'
'test2.m'
'test10.m'
'test10-old.m'
whereas the inbuilt sort returns the strings sorted according to their character order:
>> sort(B)
ans =
'test.m'
'test1.m'
'test10-old.m'
'test10.m'
'test2.m'
To use this with your filenames, simply extract the filename strings from the output of dir like this:
hasil = dir('*.jpg');
names = natsortfiles({hasil.name});
for k = 1:numel(names)
out = imread(names{k});
... image processing here
end
Note that natsortfiles is a wrapper for this function, which you will also need: