Home > Back-end >  how to find the index of an object with certain property value in an array?
how to find the index of an object with certain property value in an array?

Time:08-04

For example, I create a class 'student'

classdef student

 properties
    name
    sex
    age
 end

 methods
    function obj = student(name,sex,age)
    obj.name = name;
    obj.sex = sex;
    obj.age = age;
 end
end

and then create some objects in an array 'school'

school(1)=student(A,'boy',19)
school(2)=student(B,'girl',18)
school(3)=student(C,'boy',20)
school(4)=student(D,'girl',19)

My question is how to find the index of the objects with certain properties in the array 'school'?

For example, if I want to find students with age 19, the result will be index [1,4]

If I want to find students with age 19 and sex 'boy', the result will be index [1]

Further question 1: how to find the row and colume index? The object with sex 'girl' and age 19 lies in row 1 colume 4.

Further question 2: if school is an cell array, how to solve above problems?

CodePudding user response:

Seems kind of homework questions. However here are the answers:

% find students with age 19,
find (  [school(:).age] == 19 )

% find students with age 19 and sex 'boy', 
find (  [school(:).age] == 19 & strcmp( { school(:).sex }, 'boy'   ) )

% how to find the row and colume index? 
[row, col] = ind2sub( size(school), find (  [school(:).age] == 19 & strcmp( { school(:).sex }, 'girl'   ) ) )

Considering the last question, I would convert the cell of school objects back into an array and do as shown above.

CodePudding user response:

If school is a cell array so you have

school = cell(4,1);
school{1}=student(A,'boy',19)
school{2}=student(B,'girl',18)
school{3}=student(C,'boy',20)
school{4}=student(D,'girl',19)

Then you can loop through them to evaluate your conditions. A concise way to do this is with cellfun:

boolAge19 = cellfun( @(x) x.age == 19, school );
idxAge19  = find( boolAge19 );
boolBoy   = cellfun( @(x) strcmp( x.sex, 'boy' ), school );
idxBoy    = find( boolBoy );
boolBoyAnd19 = boolAge19 & boolBoy;
idxBoyAnd19  = find( boolBoyAnd19 );

You can of course skip intermediate steps, the lines just get dense

idxBoyAnd19 = find( cellfun( @(x) x.age == 19, school ) & ...
                    cellfun( @(x) strcmp( x.sex, 'boy' ), school ) );
  • Related