load several (one after another ) .mat Files via a For-Loop Job
270 views (last 30 days)
Hello, i have a Program that is in the Folder-Directory: Main. And i have some several numbered .mat-Files with the Variable Buff that are in the Folder Directory Main/Combination:
...and so on
My Program should load the first combinations_1.mat and to something:
for I = 1:size(Buff,1)
% calculate some stuff
After the Loop is done it should load combinations_2 and start the Loop again
My Idea is:
d = dir('*.mat'); % only looking for .mat-Files
Number_mat = length(d); % number of .mat-Files
load(['combinations_' num2str(i) '.mat'])
But i no idea how i can this combine with the For-Loop. Hope everybody understand my aim, big thanks
More Answers (1)
Image Analyst on 17 Jan 2013
You can use dir() to get a list of the filenames. Then you should check that the variable is actually in the mat file. Try this. It's a fairly robust adaptation of code already in the FAQ.
myFolder = 'Main/combinations'; % May need to correct this.
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
filePattern = fullfile(myFolder, 'combinations*.mat');
matFiles = dir(filePattern);
for k = 1:length(matFiles)
matFilename = fullfile(myFolder, matFiles(k).name)
matData = load(matFilename); % Retrieves a structure.
% See if Buff actually exists in the data structure.
hasField = isfield(matData, 'Buff');
% Alert user in popup window.
warningMessage = sprintf('Buff is not in %s\n', matFilename);
% It's not there, so skip the rest of the loop.
continue; % Go to the next iteration.
% If you get to here, Buff existed in the file.
Buff = matData.Buff; % Extract the Buff from the structure.
for row = 1 : size(Buff,1)
% Calculate some stuff