Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run the same code with many files (different file name in same directory) in Matlab?

I have a thousand .dat files to run with the same program. Is there any faster way or script to run it automatically instead of run them one by one? The .dat files have different filenames.

The program is something like:

fid=fopen('**abd**.dat');
C=textscan(...);
...
save('**abd**.txt',data);

The abd is the file name. I have thousands of files with different file names. It is a bit annoying by keep copying and pasting those filenames into the program and run it. Anyone got a faster way or code for this?

like image 449
weird Avatar asked Jul 01 '11 16:07

weird


2 Answers

you can use "dir" to get a list of files, and then process them in a loop like this.

fns = dir('*.dat');
for i = 1:length(fns)
    fid = fopen(fns(i).name);
    C = textscan(...);
    fclose(fid);
    save([fns(i).name,'.dat'],data);

end
like image 90
BlessedKey Avatar answered Sep 25 '22 22:09

BlessedKey


Rethink the problem. Write one script to read a text file of file names and strings. Then you've got 2 files, not thousands.

like image 24
Marc Avatar answered Sep 24 '22 22:09

Marc