How do I add to a structure in a for loop?

69 ビュー (過去 30 日間)
AKMS
AKMS 2023 年 3 月 20 日
編集済み: Stephen23 2023 年 3 月 21 日
I have a bunch of matlab variable files in a directory that I want to load into one structure for analysis on later. Right now I can get the file to load into the structure but it gets replaced when the for loop starts over. It might be something simple I'm overlooking; I just don't use MATLAB often.
files = dir('*.mat');
for i=1:length(files)
S=load(files(i).name,"-mat");
end

採用された回答

Stephen23
Stephen23 2023 年 3 月 21 日
編集済み: Stephen23 2023 年 3 月 21 日
Rather than creating another variable, simply store the imported data in the same structure that you are already using. I also improved your code by using a path to the files, so the data files can be saved anywhere.
P = '.'; % absolute or relative path to where the MAT files are saved.
S = dir(fullfile(P,'*.mat')); % this returns a structure array, so why not use it?
for k = 1:numel(S)
F = fullfile(P,S(k).name);
S(k).data = load(F,"-mat");
end
S = [S.data] % optional concatenation, assumes compatible structure fields.

その他の回答 (1 件)

Cameron
Cameron 2023 年 3 月 21 日
編集済み: Cameron 2023 年 3 月 21 日
files = dir('*.mat');
for i=1:length(files)
S{i,1}=load(files(i).name,"-mat");
end

カテゴリ

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