Have class vector; how obtain vector of a field?

조회 수: 5 (최근 30일)
David W Purcell
David W Purcell 2020년 4월 1일
댓글: David W Purcell 2020년 4월 1일
Hello,
I have a vector (1D array) of a class that has several fields.
When working with my class, I would like to sometimes obtain a simple vector of a specific field, but I have only been able to do that with a for loop. There must be a better way!
For example, I have a class to represent a person called meep. A field within meep is age.
If I have vector containing 1000 meep, I might like to extract a numeric vector containing just the ages.
I thought something like
ages=meep(:).age;
might do the trick, but it just gives the age of the last element of the meep vector. I've resorted to this static helper function within my class:
function param=paramVec( mVec, field )
n=length(mVec); %number of meeps; object mVec is expected to be a vector
param=-99*ones(n,1); %one spot per meep
for i=1:n %go through meep vector
param(i)=mVec(i).(field);
end
end %end of return vector of requested parameters static function
Can someone suggest a more sensible and faster running approach?
Thank you, David

채택된 답변

Guillaume
Guillaume 2020년 4월 1일
ages = [meep.age]; %same as: ages = horzcat(meep.age);
%or
ages = vertcat(meep.age); %to vertically concatenate all the values
See the documentation on comma separated lists for details of how this work.
If for some reason, the fields/properties cannot be concatenated (because they don't have a common size in at least one dimension), then:
ages = {meep.age}; %to store them as a cell array
  댓글 수: 1
David W Purcell
David W Purcell 2020년 4월 1일
Thank you for your help. That is much better!!!!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by