In below code we have a population 'P' of size 'NP' which has two fields 'Position' and 'Cost'. I need to sort the entire population 'P' with respect to field 'Cost' and select top p elements (say p = 4).
clc; clear all;
varMin = -5;
varMax = 5;
D = 3;
VarSize = [1 D];
NP = 10;
empty_individual.Position = [];
empty_individual.Cost = [];
P = repmat(empty_individual, NP, 1);
CostFunction = @(x) sphere(x);
for i = 1:NP
P(i).Position = unifrnd(varMin, varMax, VarSize);
P(i).Cost = CostFunction(P(i).Position);
end
sphere.m
function ret = sphere(x)
ret = sum(x.^2);
end