Retrieve data from a nested structure
조회 수: 47 (최근 30일)
이전 댓글 표시
Hi,
I am looking for some help with extracting data from a nested structure. I have a structure like that shown below.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/170627/image.jpeg)
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
댓글 수: 0
답변 (2개)
Martin Dale
2021년 12월 8일
% use a 2 stage process ( or more stages for a deeper nested structure)
tmp = [data.prop];
areas = [tmp.area];
댓글 수: 0
Walter Roberson
2018년 2월 19일
myData = [data.prop.Area];
댓글 수: 5
Walter Roberson
2021년 12월 8일
N = 10;
data.prop = struct('Area', num2cell(rand(1,N)), 'Perimeter', num2cell(randi(50,1,N)), 'Centre', num2cell(rand(N,2),2).');
data.prop
[data.prop.Area]
You can see that my data.prop is a non-scalar structure and that it still works.
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!