For a class object with a property that is an array of class objects, how to find the element in that array with highest property value

조회 수: 4 (최근 30일)
I have a class object, where one of the properties of the object is an array of objects of a different class. So ClassA has a property called 'population' which is an array of ClassB objects. ClassB has a property called 'fitness'. I want to find the element in the 'population' that has the highest fitness.
classdef ClassA < handle
properties
population ClassB
end
methods
function obj = ClassA(target, popSize)
n = 1;
while n <= popSize
obj.population(n) = ClassB(target);
n = n + 1;
end
end
end
classdef ClassB < handle
properties
genes
fitness
end
end
The ClassA constructor works. I'm able to fill the array with ClassB objects, each of them having a unique value for ClassB.fitness. I've tried the max() function, as seen below:
target = 'Hello!';
popSize = 100;
obj = Population(target,popSize);
[M, I] = max(obj.population.fitness)
But, to no avail. Any suggestions on how to find the max fitness without using a loop?
Thank you!

채택된 답변

Richard Brown
Richard Brown 2019년 11월 5일
Your
obj.population.fitness
line returns comma separated values, not an array. So just enclose it in brackets:
[M, I] = max([obj.population.fitness])

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Graphics Object Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by