For loop to store one matrix from multiple files to a structure

3 ビュー (過去 30 日間)
John Kim
John Kim 2023 年 2 月 17 日
コメント済み: Stephen23 2023 年 2 月 21 日
Hello everyone,
I am trying to create a for-loop to go through multiple files store a single matrix from each file into a structure.
The code I am currently using allows me to pull the necessary matrix but will not store them all into one structure
cd 'C:\Users\Document\Data'
a = dir('*.mat');
b = 1;
filename = a(b).name;
for i=1:size(a,1)
tempdata = importdata(filename);
all_new = tempdata.results;
b = b+1;
end
By the end, I am hoping to have a structure that contains the matrix "tempdata.results" from all the files in 'C:\Users\Document\Data'.
Thank you!

採用された回答

Walter Roberson
Walter Roberson 2023 年 2 月 17 日
projectdir = 'C:\Users\Document\Data';
dinfo = dir(fullfile(projectdir, '*.mat'));
filenames = fullfile( {dinfo.folder}, {dinfo.name});
numfiles = length(filenames);
all_new(numfiles,1) = struct('results',[]); %pre-allocate
for K = 1 : numfiles
tempdata = load(filenames{K}, 'results'); %should contain only results
all_new(K) = tempdata;
end
It would probably be more common to use a cell array than a struct array, but you specifically asked for a structure.
In the case where the arrays are all the same size, you can often gain performance advantages by using a multidimensional array of data instead of a cell array or struct array.
  2 件のコメント
John Kim
John Kim 2023 年 2 月 20 日
Thank you very much!
It worked perfectly.
Could you elaborate on what you mean by multidimensional array?
Stephen23
Stephen23 2023 年 2 月 21 日
"Could you elaborate on what you mean by multidimensional array?"

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

その他の回答 (1 件)

Stephen23
Stephen23 2023 年 2 月 18 日
編集済み: Stephen23 2023 年 2 月 18 日
P = 'C:\Users\Document\Data';
S = dir(fullfile(P,'*.mat'));
for k = 1:numel(S)
F = fullfile(S(k).folder,S(k).name);
S(k).data = load(F);
end
out = [S.data] % one structure

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by