How to add and save struct in multiple .matfile for loop ?

HI, I have one folder name studygroup and a list of 26 .mat file in that folder. Each mat file contains 55 structure. I would like to add one struct (Struct.status = 'yes') for each .matfile using for loop, Is it possible?
directory{1,1} = 'studygroup'
files = dir(sprintf('%s/*.mat',directory{1,1})); % list all the .mat files. (26 .matfile )
for i=1:length(files)
load(sprintf('%s/%s',directory{1,1}, files(i).name));
Struct.status = 'yes';
save ('files', 'Struct')
end
what is the best way to add and save struct in multiple matfile ?
thank you

2 Comments

my mat files :
'FT03419.mat'
'FT07273.mat'
'FT10398.mat'
'FT17798.mat'
'FT18192.mat'
'FT19529.mat'
'FT29060.mat'
'FT34961.mat'
'FT34988.mat'
'FT36328.mat'
'FT38748.mat'
'FT41119.mat'
'FT51999.mat'
'FT58661.mat'
'FT64654.mat'
'FT73960.mat'
'FT77332.mat'
'FT77509.mat'
'FT78810.mat'
'FT80227.mat'
'FT81069.mat'
'FT81859.mat'
'FT83843.mat'
'FT94664.mat'
'FT97585.mat'
'FT99193.mat'
when I try my code, Struct.status= 'aki' do not loop for all mat file.

Sign in to comment.

 Accepted Answer

Hi Farhah,
As per my understanding you want to add and save a new structure to multiple .mat files in the "studygroup" folder.
Alter your code as follows to accomplish the same.
directory = 'studygroup';
files = dir(fullfile(directory, '*.mat')); % list all the .mat files
for i = 1:length(files)
matFilePath = fullfile(directory, files(i).name);
load(matFilePath); % Load the .mat file
% Add the new structure
newStruct.status = 'yes';
% Save the updated .mat file
save(matFilePath, 'newStruct', '-append');
end
This code loops over each .mat file in the "studygroup" folder, loads the file, adds a new structure newStruct with the status 'yes', and saves the updated .mat file with the -append flag to preserve the existing data.
Make sure that the .mat files in the "studygroup" folder have the appropriate permissions for modification.
I hope this resolves the issue.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!