MATLAB: How to sort the struct array after reading number of images using dir command

image analysisimage processingoptimization

Hi,
I am reading images thru 'dir' command from a folder but those are unsorted , I am expecting them as sorted….
file2=dir(file); // file contains path to the folder where I stored the images
for k = 1 : numel(file2)
im = imread(file2(k).name);
folder1=sprintf('%s%s%s%d',targetfolder,index,fi,j);
imwrite(im,[folder1,'.jpg']);
j=j+1;
end

Best Answer

"I am reading images thru 'dir' command from a folder but those are unsorted , I am expecting them as sorted...."
The order of the output of dir is determined by the OS and is not specified.
You can sort filenames very easily by using my FEX submission natsortfiles, which provides an alphanumeric sort for filenames (i.e. so that any numbers in the filenames are sorted into numeric order). You will need to download it, unzip it, and place the Mfiles on the MATLAB Search Path (e.g. in the current directory):
It is easy to use, and there are example in the Mfile and HTML documentation. Here is a basic working example:
D = 'C:\Test';
S = dir(fullfile(D,'*.txt'));
N = natsortfiles({S.name});
for k = 1:numel(N)
filename = fullfile(D,N{k})
...
end
"How to sort the struct array after reading number of images using dir command": if you really want to do this then use the second output from natsortfiles:
S = dir(...);
[~,idx] = natsortfiles({S.name});
S = S(idx);