How can I refer to all fields (of a particular level) within a structure?

조회 수: 3 (최근 30일)
AR
AR 2018년 7월 5일
댓글: AR 2018년 7월 6일
Example: I have a struct such as this (simplified): Students.Gender.Height
I want to refer to and operate upon all fields regardless of gender. So, Students.Boy.6feet or Students.Girl.6feet would both be affected by the operation. Not a great example, but I hope I am conveying the need here. Is there a wildcard or () or {} type of way to index or refer to all fields of the "gender" level?

채택된 답변

James Tursa
James Tursa 2018년 7월 5일
What "works" is probably going to depend on what is contained in the sub-fields and what you intend to do with this data downstream in your code. E.g., for your simplistic example if you wanted to extract the data (assuming the Height was scalar):
result = cellfun(@(x)Students.(x).Height,fieldnames(Students))
That would give you a result variable that you could use downstream.
Maybe you could give us more detail on the fields of your structure, and what operations you intend.
  댓글 수: 2
AR
AR 2018년 7월 5일
Thanks James. I was probing a little ahead to figure out the best way to script things. As of now, I am not sure exactly what I want to do - I will have to write a little more and then get back to you on this question.
AR
AR 2018년 7월 6일
Ok, here's what I was needing to do:
I used your method to get me the result variable, call it r.
I would like to pass the value in r (which is a cell array) to another similar structure. Let's call this RivalStudent.
So, in the end, RivalStudent.(x).Height = Student.(x).Height, the latter being r, of course. How do I assign RivalStudents of both genders the same heights as those of the Students? TIA.
In reality, these are not students and genders, but the original struct looks like this: A.B(1 of 5 fields).C(1 of 40 fields, each of which contains a cell array of numbers or strings).

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by