listing files order text file dir

I would like to list files in my current directory of the format
ab1.mat
ab2.mat
ab3.mat
onwards in a text file in proper numerical order. This is what I have so far, it writes the names to the txt file but does not do it in order.
fff = fopen('names.lst','w+');
A = dir('ab*.mat');
fileNames = { A.name };
for i=1:length(fileNames);
fprintf(fff,'%s',sprintf( '%s\n',fileNames{i}));
I do not want to use a dedicated script I would just like to modify this code to do what i want it to, or another piece of short code.
Thanks Thanks!

1 Comment

Please do not edit all the meaningful content out of a Question, and please do not start new questions on the same topic. You can reply to existing questions if you want to add more information.
As you ruined your previous Question on this topic, I moved the relevant answer from there over to here and will delete that previous Question.

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 16 Aug 2012
The order of files returned by dir() is "whatever is returned by the underlying operating system". In turn operating systems might use different orderings depending on the variety of filesystem being used.
You must therefore sort the names before you print them out. See http://www.mathworks.com/matlabcentral/fileexchange/8399-sortn-sort-textual-lists. You are not required to use that script, but it will show you how the task can be done.
Note: there is no option to dir() to return the files in "numeric" order, and there is no option to sort() to sort the files in "numeric" order. You need to program the sorting yourself, or use someone else's already-written sorting function.

Categories

Asked:

on 16 Aug 2012

Community Treasure Hunt

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

Start Hunting!