Is there a way to perform queries on object collections?

1 visualización (últimos 30 días)
tombola
tombola el 16 de Dic. de 2011
Hi, I know I can use arrayfun to call a method on each object in an array, but is there a way to perform queries across the array?
This is a made up example, but if I have a class
MATLAB code
classdef Employee
properties
salary = 0; %Set later
end
And I have an array of instances of this class
MATLAB code
staff = [employee1 employee2 employee3 ..... employeeN];
Is there an easy way I can write a query to get, say, the 3 Employees with the largest salarys?
Thanks for any help, just give me a shout if this isn't clear.
Tom.

Respuesta aceptada

Darik
Darik el 16 de Dic. de 2011
Use comma separated list syntax
staff = [employee1 employee2 employee3 ..... employeeN];
salary = [staff.salary];
[~, i] = sort(salary, 2, 'descend');
top3 = staff(i(1:3))
Keep in mind that if you ever want to subclass your Employee class (into e.g. Secretary and Manager classes) you won't be able to store them all in the same array without converting them all into simple Employee objects.
  2 comentarios
tombola
tombola el 19 de Dic. de 2011
That's brilliant, thanks a lot.
Is there any way to remove NaNs from the list please? So if salary is NaN then it doesn't get included in a "top3" or "bottom3" sort?
tombola
tombola el 19 de Dic. de 2011
Hi, I've worked it out.
nanPositions=[isnan(salary)]
staff(nanPositions)=[]
salary(nanPositions)=[]
Then sort. Thanks a lot for the answer above.

Iniciar sesión para comentar.

Más respuestas (1)

Sean de Wolski
Sean de Wolski el 16 de Dic. de 2011
Instead of having each employee be its own variable ( like this ) have an employer class with employees as properties and salaries as properties.
There are many example available from the documentation for classdef.
  1 comentario
tombola
tombola el 16 de Dic. de 2011
Hi, I definitely need it done the way in the example thanks.

Iniciar sesión para comentar.

Categorías

Más información sobre Construct and Work with Object Arrays en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by