Getting data from more than one field in a struct
3 views (last 30 days)
Show older comments
Probably shouldn't have used a struct like this but wondering if its possible.
I have a struct Data which has a field houses which has field rooms. And I have XDimension , YDimension etc... for each room.
I can get the x dimension of room 1 in house 1 by doing:
ans=Data.Houses(1).Rooms(1).XDimension
How do I get all the XDimension values for all rooms in all houses.
ans=Data.Houses(:).Rooms(:).XDimension
gives error:
Expected one output from a curly brace or dot indexing expression, but there were 4 results.
Is it possible to do this without using a loop?
Cheers,
Steve
1 Comment
Mario Malic
on 19 Feb 2021
It's doable without for loop, but not viable for high number of houses.
[Data.Houses(1).Rooms(:).XDimension; Data.Houses(2).Rooms(:).XDimension]
% output of this is number of houses x number of rooms
Maybe someone else will provide proper/better answer on this question.
Answers (1)
Walter Roberson
on 19 Feb 2021
cell2mat(arrayfun(@(HOUSE) [HOUSE.Rooms.XDimension], Data.Houses(:), 'Uniform', 0))
Assuming that XDimension is a scalar, the [] part should become a row vector contained in a cell array, and the (:) on Data.Houses would cause the cells to be arranged in a column. From there cell2mat() should turn it into a numeric matrix with one row per Houses and one column per Rooms ... assuming that every house has the same number of rooms.
If different houses have different number of rooms, you need to define your desired output in a way that you can still distinguish between the different houses. Unless, that is, you do not need to, such as if you need something like the average length of rooms over all houses, in which case you can
cell2mat(arrayfun(@(HOUSE) vertcat(HOUSE.Rooms.XDimension), Data.Houses(:), 'Uniform', 0))
0 Comments
See Also
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!