How to load files identified by the matlab function of "dir"?
75 views (last 30 days)
I have many files in a folder named "mat_files". What I want to do is to load the files and get their values. Below is my code:
a = dir('mat_files');
for i = 3:length(a);
filename = a(i).name;
load strcat('mat_files/', filename);
This is the error:
Error using load
Unable to read file 'filename': no such file or directory.
When I type a(3).name in the command window, I get the correct filename of "ex0219.mat". Of course, I can load the data by typing "load ex0219.mat". Clearly load a(3).name does not work. I also tried load (a(3).name), which does not work either.
Image Analyst on 8 Dec 2013
See the second code example in the FAQ: http://matlab.wikia.com/wiki/FAQ#How_can_I_process_a_sequence_of_files.3F
A smiple modification gives you the answer:
myFolder = 'C:\users\leon\documents'; % or whatever.
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
filePattern = fullfile(myFolder, '*.mat');
matFiles = dir(filePattern);
for k = 1:length(matFiles)
baseFileName = matFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
storedStructure = load(fullFileName);
% Now do whatever you need to do with the structure you recalled.