Acces data in nested structure

조회 수: 14(최근 30일)
Rob Weh
Rob Weh 2019년 6월 4일
댓글: Bjorn Gustavsson 2019년 6월 4일
Hi everyone,
I have a structure like this:
S.various_substructures.value1.x and S.various_substructures.value1.y
various_substructures are structures of varying fieldnames while the following substructures have the same names. The last structure contains arrays x and y.
I tried it with arrayfun without succes. Any idea to acces the data without a loop?
TIA, Rob
  댓글 수: 3
Bjorn Gustavsson
Bjorn Gustavsson 2019년 6월 4일
@Jan: ...and we all have memories of thinking: "if - if only..."

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

채택된 답변

Stephen23
Stephen23 2019년 6월 4일
편집: Stephen23 2019년 6월 4일
"Any idea to acces the data without a loop?"
Not really.
You can either use an explicit for loop or an implicit loop using arrayfun or structfun:
>> S.A.value1.x = 1;
>> S.A.value1.y = 11;
>> S.B.value1.x = 2;
>> S.B.value1.y = 22;
>> S.C.value1.x = 3;
>> S.C.value1.y = 33;
>> X = structfun(@(s)s.value1.x,S)
X =
1
2
3
>> Y = structfun(@(s)s.value1.y,S)
Y =
11
22
33
  댓글 수: 1
Rob Weh
Rob Weh 2019년 6월 4일
Damn, was trying structfun before but seems I messed something up... :\ Many thanks Stephen for your fast reply!!!

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

추가 답변(2개)

Sayyed Ahmad
Sayyed Ahmad 2019년 6월 4일
if your various_substructures is an array you can access the value like follow:
for i=1:5
s.var(i).val1.x=i;
s.var(i).val1.y=i^2;
end
x=s.var(3).val1.x;
y=s.var(3).val1.y;

Raghunandan V
Raghunandan V 2019년 6월 4일
Hi,
You can treat the variable name as string.
  • First you should store all the various_subStructures in an array(or cell) in form of string.
  • Make a loop and get the name of the variables that you want in string format.
  • Then convert the name in the form of string to variable name using commands like genvarname and eval like this
Regards,
Raghunandan V
  댓글 수: 2
Raghunandan V
Raghunandan V 2019년 6월 4일
Thanks, I didn't know this

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

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by