How to use union operator

1 view (last 30 days)
Atinesh Singh
Atinesh Singh on 27 Mar 2017
Answered: KSSV on 27 Mar 2017
Consider the below code where I'm generating two random Population A and P. I need to make union of these two population. I tried using union operator, But it's not working.
clc; clear all;
varMin = -5;
varMax = 5;
D = 3; % Dimension
VarSize = [1 D]; % Decision Variables Matrix Size
NP1 = 10; % Population 1 size
NP2 = 3; % Population 2 size
empty_individual.Position = [];
empty_individual.Cost = [];
P = repmat(empty_individual, NP1, 1); % Population 1
A = repmat(empty_individual, NP2, 1); % Population 2
CostFunction = @(x) sphere(x);
%%Generating random population 1
for i = 1:NP1
P(i).Position = unifrnd(varMin, varMax, VarSize);
P(i).Cost = CostFunction(P(i).Position);
end
%%Generating random population 2
for i = 1:NP2
A(i).Position = unifrnd(varMin, varMax, VarSize);
A(i).Cost = CostFunction(A(i).Position);
end
sphere.m
function ret = sphere(x)
ret = sum(x.^2);
end
How to make union of A and P.

Accepted Answer

KSSV
KSSV on 27 Mar 2017
% megre two structure
iwant = [P ; A] ;
% get unique values
[val,idx] = unique([iwant.Cost]) ;
iwant = iwant(idx) ;

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!