Retrieve data from a nested structure

Hi,
I am looking for some help with extracting data from a nested structure. I have a structure like that shown below.
I can call a single value from the structure easily e.g data.prop(1).Area will give me the value of Area from the first prop structure.
I wish to extract easily all of a certain field, the only way I can currently do this is with a loop. For example I might wish to make an array with all of the Areas.
myData = data.prop(1:3).Area
However this doesn't work.
My current solution is to loop through the structure as follows:
for i = 1:length(data)
myData(i,1) = data.prop(i).Area
end
If there is a better way to achieve this I would be very interested. Thank you for the help

回答(2 个)

% use a 2 stage process ( or more stages for a deeper nested structure)
tmp = [data.prop];
areas = [tmp.area];
myData = [data.prop.Area];

5 个评论

Thanks, I have tried this but I get this answer,
Expected one output from a curly brace or dot indexing expression, but there were 1003 results.
Not sure what the problem is?
You could get that error if you omitted the [] that I showed, or if data is not a scalar structure (but if data were not a scalar structure you would have received an error in your for loop version.)
Example:
N = 10;
data.prop = struct('Area', num2cell(rand(1,N)), 'Perimeter', num2cell(randi(50,1,N)), 'Centre', num2cell(rand(N,2),2).');
[data.prop.Area]
the substructure prop is a non-scalar structure. The [] extraction cannot work.
Unfortunately, the loop is the only option. That's one of the reason I dislike multilevel structures.
AHH, I think this is the issue, each of the prop is a structure holding a field, Area, Perimeter etc which each has one value. The loops are working but I just read about avoiding loops for efficiency and that its a bad coding practice.
I started using structures as its the only way I found of naming columns so that I know what that column contains.
N = 10;
data.prop = struct('Area', num2cell(rand(1,N)), 'Perimeter', num2cell(randi(50,1,N)), 'Centre', num2cell(rand(N,2),2).');
data.prop
ans = 1×10 struct array with fields:
Area Perimeter Centre
[data.prop.Area]
ans = 1×10
0.9392 0.1636 0.5417 0.4702 0.3263 0.5196 0.4143 0.4565 0.1550 0.5646
You can see that my data.prop is a non-scalar structure and that it still works.

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by