How do I iterating through a struct with several levels?

8 ビュー (過去 30 日間)
HabenG
HabenG 2021 年 12 月 21 日
コメント済み: Voss 2021 年 12 月 22 日
I have a struct thats three levels deep and would like to iterate through the second level while keeping the last level a constant and save the data.
% This works but how do i iterate through d1,d and d3?
for i = 1 : 3
j.d(i) = data.d1(:,4)
end
  1 件のコメント
Stephen23
Stephen23 2021 年 12 月 21 日
編集済み: Stephen23 2021 年 12 月 21 日
"I have a struct thats three levels deep"
Actually the uploaded data is a simple scalar structure, each field of which contains a numeric array:
S = load('data.mat');
data = S.data
data = struct with fields:
d1: [458×5 double] d2: [1915×5 double] d3: [3737×5 double]
Note that simpler data design would use indexing rather than forcing pseudo-indices into the fieldnames, e.g. by using a non-scalar structure or a cell array. Using indexing would make your code simpler than the current approach.
Note also that fields can change order.

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

採用された回答

Voss
Voss 2021 年 12 月 21 日
First, a point of clarification: the mat-file attached to the question contains a struct with three fields, each of which is an array, rather than a struct containing a struct containing another struct, which is what "a struct that's three levels deep" sounds like to me.
To iterate through the fields of a struct, you can use dynamic field names and the fieldnames function. For instance, to create a struct j that has the same fields as the struct data from the mat-file, but with only the 4th column from each, you can do this:
load data
display(data);
data = struct with fields:
d1: [458×5 double] d2: [1915×5 double] d3: [3737×5 double]
j = struct();
f = fieldnames(data);
for i = 1:numel(f)
j.(f{i}) = data.(f{i})(:,4);
end
display(j);
j = struct with fields:
d1: [458×1 double] d2: [1915×1 double] d3: [3737×1 double]
  2 件のコメント
HabenG
HabenG 2021 年 12 月 22 日
My mistake. I should've phrased the question better but thank you for the help.
Voss
Voss 2021 年 12 月 22 日
No problem. I just wanted to clarify the terminology for future reference. Describing mathematical objects in English (or any human language) is bound to be ambiguous, but describing them in MATLAB (or any programming language) is unambiguous (hopefully).

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by