How can I read all text files in a folder without making a struct?

Using the function x = dir ('*.txt') gives a struct (1x127)
I want to read my 127 text files (matrices) in individually, not in a struct, how can I do it?
Alternatively how can I extract the 127 matrices from a struct?
Thank you in advance for any help

 Accepted Answer

x = dir ('*.txt') does return a struct but it is a struct of information about the files, not a struct of the data. It basically tells you want the names of the files are (and sizes and last modified and things like that.) You still need to do the loading.
For example,
dinfo = dir('*.txt');
for K = 1 : length(dinfo)
thisfilename = dinfo(K).name; %just the name
thisdata = load(thisfilename); %load just this file
fprintf( 'File #%d, "%s", maximum value was: %g\n', K, thisfilename, max(thisdata(:)) ); %do something with the data
end
If you already know the names then you don't need to use dir() to tell them to you. For example,
for K = 1 : 42
thisfilename = sprintf('qwerty_%04d.txt', K);
thisdata = load(thisfilename); %load just this file
fprintf( 'File #%d, "%s", maximum value was: %g\n', K, thisfilename, max(thisdata(:)) ); %do something with the data
end
to load qwerty_0001.txt, qwerty_0002.txt ... qwerty_0042.txt

5 Comments

Even if you do know the names, I still would do a dir to check that the files I'm expecting are actually there. There's nothing more infuriating than having your code processing files for 20 minutes only to stop with an error because the last file in your list was mispelled / not present for a reason and having to start all over again.
Thanks for your help, I am trying to utilise the first code you suggested, an interesting error occurs.
Error using load
Unable to read file 'TOP_0001.txt'. No such file or
directory.
(TOP_0001.txt is the first file that should load) I don't see what the problem is, any suggestion? Obviously it would have to find the file in that directory to know it's name so the error makes no sense...
If you are applying dir() against a different directory then the name component returned does not have the directory name included.
dir_to_search = 'C:\Programs and Data\Robert\Test173\';
txtpattern = fullfile(dir_to_search, '*.txt');
dinfo = dir(txtpattern);
for K = 1 : length(dinfo)
thisfilename = fullfile(dir_to_search, dinfo(K).name); %just the name
thisdata = load(thisfilename); %load just this file
fprintf( 'File #%d, "%s", maximum value was: %g\n', K, thisfilename, max(thisdata(:)) ); %do something with the data
end
In the "thisfilename " what is the "name"?
ok. I understood this is the file's name.

Sign in to comment.

More Answers (0)

Categories

Products

Community Treasure Hunt

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

Start Hunting!