How to sort a Matrix
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Atinesh Singh
am 27 Mär. 2017
Beantwortet: Andrei Bobrov
am 27 Mär. 2017
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; % Dimension
VarSize = [1 D]; % Decision Variables Matrix Size
NP = 10; % Population size
empty_individual.Position = []; % Field 1
empty_individual.Cost = []; % Field 2
P = repmat(empty_individual, NP, 1); % Population
CostFunction = @(x) sphere(x);
%%Generating random population
for i = 1:NP
P(i).Position = unifrnd(varMin, varMax, VarSize);
P(i).Cost = CostFunction(P(i).Position);
end
% add Code here
sphere.m
function ret = sphere(x)
ret = sum(x.^2);
end
0 Kommentare
Akzeptierte Antwort
Andrei Bobrov
am 27 Mär. 2017
p = 4;
data = [P.Cost]';
[~,ii] = sort(data);
out = P(ii(1:p));
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!