Addee
Addee

Reputation: 671

Reading all the files in sequence in MATLAB

I am trying to read all the images in the folder in MATLAB using this code

flst=dir(str_Expfold);

But it shows me output like this. which is not the sequence as i want. Can anyone please tell me how can i read all of them in sequence? Image

for giving downmark, please explain the reason for that too.

Upvotes: 2

Views: 440

Answers (2)

nkjt
nkjt

Reputation: 7817

By alphabetical order depth10 comes before depth2. If at all possible, when creating string + num type filenames, use a fixed width numerical part (e.g. depth01, depth02) - this tends to avoid sorting problems.

If you are stuck with the filenames you have, and know the filename pattern, though, you can not bother using dir at all and create your filename list in the correct order in the first place:

for n = 1:50
   fname = sprintf('depth%d.png',n);
   % code to read and process images goes here
end

Upvotes: 3

Javi
Javi

Reputation: 3610

From the Matlab forums, the dir command output sorting is not specified, but it seems to be purely alphabetical order (with purely I mean that it does not take into account sorter filenames first). Therefore, you would have to manually sort the names. The following code is taken from this link (you probably want to change the file extension):

list = dir(fullfile(cd, '*.mat'));
name = {list.name};
str  = sprintf('%s#', name{:});
num  = sscanf(str, 'r_%d.mat#');
[dummy, index] = sort(num);
name = name(index);

Upvotes: 3

Related Questions