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

조회 수: 11 (최근 30일)
farhah muhammad
farhah muhammad 2023년 6월 20일
편집: Walter Roberson 2023년 6월 20일
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
farhah muhammad
farhah muhammad 2023년 6월 20일
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'
farhah muhammad
farhah muhammad 2023년 6월 20일
when I try my code, Struct.status= 'aki' do not loop for all mat file.

댓글을 달려면 로그인하십시오.

채택된 답변

Shishir Reddy
Shishir Reddy 2023년 6월 20일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by