Batch processing using for loop

4 views (last 30 days)
Karoline Opsahl
Karoline Opsahl on 21 May 2022
Edited: Voss on 22 May 2022
I want to load multiple files using a for loop. I tried this code:
for i=1:length(files)
load(files(i) .name);
but it didn't work.
Can someone please try to figure out what I have done wrong?
Karoline Opsahl
Karoline Opsahl on 21 May 2022
only the variables form the first file in the folder was uploaded to workspace

Sign in to comment.

Accepted Answer

Voss on 21 May 2022
Edited: Voss on 21 May 2022
load with no output loads the contents of the mat file into the workspace, overwriting any variables of the same name that were already in the workspace. Therefore, if any mat file contains variables of the same name as variables in another mat file, then at the end of the loop, the values of those variables will come from the last mat file to be loaded.
To avoid this problem, you can load each mat file into a separate element of a cell array (or if all the mat files contain the same set of variable names, you can load each one into a separate element of a struct array).
Here's loading each file into an element of a cell array:
% prompt the user to select a directory:
EXAM_BEV3201_V20 = uigetdir();
% if a directory was selected ...
if ~isequal(EXAM_BEV3201_V20,0)
% get info about all acc_data*.mat files in that
% directory (no need to use cd):
files = dir(fullfile(EXAM_BEV3201_V20,'acc_data*.mat'));
% construct the full path names of those files:
files = fullfile(EXAM_BEV3201_V20,{});
% load each file, store everything in the cell array C:
C = cell(1,numel(files));
for i = 1:numel(files)
C{i} = load(files{i});
Then you can access the contents of each mat file by doing C{1}, C{2}, etc.

More Answers (1)

Image Analyst
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);
fprintf('Done loading %d mat files from folder "%s".\n', k, numFiles, folder);
See the FAQ on cd:

Community Treasure Hunt

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

Start Hunting!