フィルターのクリア

Automatically put content of structure fields in a matrix

2 ビュー (過去 30 日間)
Inti Vanmechelen
Inti Vanmechelen 2020 年 5 月 4 日
コメント済み: Inti Vanmechelen 2020 年 5 月 7 日
Hi all,
For the following structure:
A.TEST=rand(15x8);
A.TEST1=rand(15x8);
A.TEST2=rand(15x8);
A.TEST3=rand(15x8);
A.TEST4=rand(15x8);
A.TEST5=rand(15x8);
I would like to find an optimal way to create a new matrix (let's say B) that contains all values from TEST to TEST5 concatenated vertically, which would be B = (15*5,8).
Preferabally automatically, since my real dataset is much bigger.
Thanks!
  2 件のコメント
Stephen23
Stephen23 2020 年 5 月 5 日
編集済み: Stephen23 2020 年 5 月 5 日
Better data design would make your code simpler too, e.g. a non-scalar structure:
A.S(1).TEST = rand(15,8)
A.S(2).TEST = rand(15,8)
A.S(3).TEST = rand(15,8)
A.S(4).TEST = rand(15,8)
A.S(5).TEST = rand(15,8)
M = vertcat(A.S.TEST) % <- this is all you need
Inti Vanmechelen
Inti Vanmechelen 2020 年 5 月 7 日
I've changed my structure towards your proposal. Indeed easier.
I'm learning everyday, thanks for the tip!

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

採用された回答

darova
darova 2020 年 5 月 4 日
編集済み: darova 2020 年 5 月 4 日
Try getfield
fnames = fieldnames(A);
B = [];
for i = 1:length(fnames)
b1 = getfield(A,fnames{i});
B = [B; b1];
end
Use preallocation if for loop is slow
  2 件のコメント
Inti Vanmechelen
Inti Vanmechelen 2020 年 5 月 5 日
Hi Darova,
Thank you for your help!
This solution worked, but unfortunately, I have an extra field in the structure (should've probably added that from the beginning).
Do you know how to get the same command with a structure like this?
A.S.TEST = rand(15,8)
A.S.TEST1 = rand(15,8)
A.S.TEST2 = rand(15,8)
A.S.TEST3 = rand(15,8)
A.S.TEST4 = rand(15,8)
Where S varies from 1 to 20 and TEST varies from TEST to TEST4.
I tried to figure it out but can't seem to find the correct solution.
Thank you,
Inti
darova
darova 2020 年 5 月 5 日
Use nested for loop
fnames = fieldnames(A);
B = [];
for i = 1:length(fnames)
b1 = getfield(A,fnames{i});
s = whos('b1');
if strcmp('struct',s.class) % if type of variable is 'struct'
fnames1 = fieldnames(b1);
for j = 1:length(fnames1)
b2 = getfield(b1,fnames1{j});
B = [B; b2];
end
else
B = [B; b1];
end
end

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by