How to get an array of all field elements of a 1xN structure with many fields

조회 수: 14 (최근 30일)
In this thread. @Sebastian asked how to get an array of all field elements of a 1xN structure. @AdamDanz answered, but his answer only applies to a single specified field of a struct. I want be able to loop through all fields of a struct and exact all elements of each field.
For example
S(1).a = 1; S(2).a = 2 ; S(1).b = 3 ; S(2).b = 4; S(1).c = [ 1, 2]; S(2).c = [ 3, 4]
From @AdamDanz's answer, I can write
[S(:).a]
[S(:).b]
etc., but naturally one wants to be able to loop thru all fields of S, as in
Fields = fieldnames(S);
for ii= 1:numel(Fields);
field = Fields{ii};
eval(['[S(:).' field ']']);
end
There has to be a less kludgy way of doing this!!! Thanks!
  댓글 수: 1
Stephen23
Stephen23 2021년 10월 2일
편집: Stephen23 2021년 10월 2일
"There has to be a less kludgy way of doing this!!! "
For a start, you can trivially remove that very ugly and inefficient EVAL by using dynamic fieldnames:
i.e. replace this slow, inefficient, complex, anti-pattern code:
eval(['[S(:).' field ']']) % ugh, do NOT do this!
with this neat, simple, and very efficient code:
[S(:).(field)]
or equivalently just this:
[S.(field)]
See also:
Using a FOR loop is probably the most efficient solution to your original question.

댓글을 달려면 로그인하십시오.

채택된 답변

Matt J
Matt J 2021년 10월 2일
편집: Matt J 2021년 10월 2일
I would recommend the attached file
S(1).a = 1; S(2).a = 2 ; S(1).b = 3 ; S(2).b = 4;
T=scalarize_struct(S)
T = struct with fields:
a: [1 2] b: [3 4]
  댓글 수: 3
Matt J
Matt J 2021년 10월 2일
scalarize_struct works for your modified example, too
S(1).a = 1; S(2).a = 2 ; S(1).b = 3 ; S(2).b = 4; S(1).c = [ 1, 2]; S(2).c = [ 3, 4];
T=scalarize_struct(S)
T = struct with fields:
a: [1 2] b: [3 4] c: {[1 2] [3 4]}
Leo Simon
Leo Simon 2021년 10월 3일
scalarize_struct woks perfectly, thanks very much!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2021년 10월 2일
Fields = fieldnames(S);
for ii= 1:numel(Fields);
field = Fields{ii};
[S(:).(field)]
end
[...] is the horizontal concatenation, so the line [S(:).(field)] is equivalent to:
cat(2, S(:).(field))
Maybe you want to join the vectors vertically, then use cat(1, ...). If the arrays have different sizes, you need a cell array:
{S(:).(field)}
  댓글 수: 1
Leo Simon
Leo Simon 2021년 10월 3일
Thanks @Jan, I accepted @Matt's answer because was a bit easier to work with in my case.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by