Batch processing using for loop
Show older comments
I want to load multiple files using a for loop. I tried this code:
EXAM_BEV3201_V20=uigetdir;
cd(EXAM_BEV3201_V20);
files=dir('acc_data*.mat');
for i=1:length(files)
load(files(i) .name);
end
but it didn't work.
Can someone please try to figure out what I have done wrong?
2 Comments
Voss
on 21 May 2022
"it didn't work"
What did it do (or not do) that was different than what you expected?
Karoline Opsahl
on 21 May 2022
Accepted Answer
More Answers (1)
Image Analyst
on 21 May 2022
@Karoline Opsahl, you say "only the variables form the first file in the folder was uploaded to workspace" -- that's very strange. I would think that only the last iteration would survive since the iterations overwrite all the prior variables (if the variables have the same names).
Don't use cd and don't use i (the imaginary variable) for a loop counter! Build the full filename instead.
folder = uigetdir;
files=dir(fullfile(folder, 'acc_data*.mat'));
numFiles = numel(files);
for k = 1 : numFiles
thisFileName = fullfile(files(k).folder, files(k).name);
fprintf('Loading file #%d of %d : "%s"\n', k, numFiles, thisFileName);
allMatFiles{k} = load(thisFileName);
end
fprintf('Done loading %d mat files from folder "%s".\n', k, numFiles, folder);
See the FAQ on cd:
Categories
Find more on Workspace Variables and MAT Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!