how to implement structfun using 2 variables
조회 수: 6 (최근 30일)
이전 댓글 표시
Hi all,
Is it possible to have a code which is similar to
S.value1.x = 1;
S.value2.x = 10;
S.value3.x = 17;
S1.value1.x = 12;
S1.value2.x = 11;
S1.value3.x = 13;
S2.value1.x = 142;
S2.value2.x = 11;
S2.value3.x = 113;
output1 = structfun(@(In, val)In.val.x,S,value1)
output2 = structfun(@(In, val)In.val.x,S1,value1)
Output:
output1 = 1
output2 = 12
Here I need to changing parameter.
Thanks,
Raghunandan V
댓글 수: 1
채택된 답변
Guillaume
2019년 6월 4일
Not entirely sure what you're asking, structfun applies the same function to each field of a scalar structure. It doesn't look like it's what you're after at all.
If you're asking how to get the value of a particular field having its name stored as text, yes this can be done easily
fname = 'value1';
S.(fname).x
Hopefully, your example is for illustration and you're not using numbered variables and numbered field names. Numbered anything is a flawed design and you should replace that with proper indexing:
S(1).value(1).x = 1
S(1).value(2).x = 10;
S(1).value(3).x = 17;
S(2).value(1).x = 12;
S(2).value(2).x = 11;
S(2).value(3).x = 13;
S(3).value(1).x = 142;
S(3).value(2).x = 11;
S(3).value(3).x = 113;
which completely removes the need to generate field names as strings.
댓글 수: 0
추가 답변 (1개)
Jan
2019년 6월 4일
This seems to be much easier:
field = 'value1';
output1 = S.(field).x
output1 = S1.(field).x
structfun iterates over the fields of a struct. So it is not clear why you want to use it to get the values of a nested substruct.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!