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.
  1 件のコメント
farhah muhammad
farhah muhammad 2023 年 6 月 20 日
thank you! it works! thank you

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by