필터 지우기
필터 지우기

Getting data from more than one field in a struct

조회 수: 5 (최근 30일)
Steven Brace
Steven Brace 2021년 2월 19일
답변: Walter Roberson 2021년 2월 19일
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
Mario Malic
Mario Malic 2021년 2월 19일
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.

댓글을 달려면 로그인하십시오.

답변 (1개)

Walter Roberson
Walter Roberson 2021년 2월 19일
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))

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by