Dileep
Dileep

Reputation: 55

Matlab dir('*.txt') command is not listing txt files in order

I am reading text files from a folder using dir('*.txt') in MATLAB. Text files are named 0, 4, 8, 12, ..180.txt. dir returns 0 first, then 100, then 104 and so on. Why is this happening?

Upvotes: 0

Views: 655

Answers (2)

Dev-iL
Dev-iL

Reputation: 24169

Lexicographical ordering works by looking only at the information that is required to make a decision. The information, in our case, is the ASCII value of the characters in filenames. Consider the following examples:

  • If we have two files names 10.txt and 2.txt, the listing mechanism will compare the 1st character of these files, i.e. 1 vs. 2, and will return whichever is smallest, which in this case is the 1 that belongs to 10.txt.

  • If instead we had 2.txt and 20.txt, the first character is the same, so the next character will be compared, which is either . or 0. Here, since the ASCII value of . is 46 and of 0 is 48, 2.txt will be returned first.

You can solve this by always having the maximum number of digits you need for the filenames, meaning:

0.txt    -->  000.txt
4.txt    -->  004.txt
25.txt   -->  025.txt
180.txt  -->  180.txt

Then files will be returned in the expected order.

Upvotes: 2

Shai
Shai

Reputation: 114846

If you are sensitive to the order of files and you already know their names, you don't have to use dir at all:

for ii=0:4:180
    filename = sprintf('%d.txt', ii);
    fid = fopen( fullfile('/path/to', filename), 'r' );
    % ... do the processing here
    fclose(fid);
end

Upvotes: 0

Related Questions