Acces data in nested structure

6 次查看(过去 30 天)
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 个评论
Jan
Jan 2019-6-4
The chosen representation of the data is not useful, as you see. This happens frequently in large programming jobs, because effects of the initial choice of the data structure are not clear in advance. Whenever you observe such a problem, you know that it is time for a refactoring of the complete code. If the program is clean and modular, or even better object oriented (or at least programmed in an object oriented style), there is a small number of locations, which need an adjustment of the objects.
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 个评论
Stephen23
Stephen23 2019-6-4
Do NOT do this!
Looping over nested structures will be simpler, more robust, and much more efficient.
Dynamically accessing variable names is one way that some beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know why:

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by