How do I write a partially mapped crossover that can produce multiple pairs of chromosomes
4 次查看(过去 30 天)
显示 更早的评论
From this link https://www.mathworks.com/matlabcentral/answers/448078-partially-mapped-crossover-function-for-tsp#answer_394090 , I'm able to produce a pair of chromosomes but I want to run the crossover function for multiple times to get multiple pairs of chromosomes.
I have 2 random parents data example,
P1: 1 | 3 7 | 6 4 10
P2: 2 | 3 4 | 7 6 10
The first and last genes (the number underlined) cannot be changed as they are the starting and endpoints. The other four genes are free to exchange at any cut point (need not be the same as the example).
I have tried to put the function into a for loop but it only produces a pair of chromosomes. Alternatively, I have tried to put the for loop inside the function but it results in the crossover function not functioning.
Here is my coding.
for z = 1:4
a = YY2(:,randi(y4))'; % Fist Vector Needed to be Cross
b = YY2(:,randi(y4))'; %Second Vector Needed to be Cross
child1 = zeros(1,size(a,2));
child2 = zeros(1,size(b,2));
[~,sizea]=size(a);
[~,sizeb]=size(b);
if sizea~=sizeb
print("a and b are not equal cant do crossover");
end
for i=1:100
r = randi([2,size(b,2)-1],1,2);
lo = min(r);
up = max(r);
if lo==up
continue
else
break
end
end
for i=lo:up
child1(i)=b(i);
child2(i)=a(i);
end
% child1
for i=lo:up
d=0;
for j=lo:up
if(a(i)==child1(j))
d=d+1;
break;
end
end
if d==0
crossover1(i,i,a,sizea,child1);
end
end
for q = 1:sizea
if child1(q)==0
child1(q)=a(q);
end
end
% child2
for i=lo:up
d=0;
for j=lo:up
if(b(i)==child2(j))
d=d+1;
break;
end
end
if d==0
crossover2(i,i,b,sizeb,child2);
end
end
for q = 1:sizeb
if child2(q)==0
child2(q)=b(q);
end
end
S = child1';
T = child2';
odd = 2*z-1;
even = 2*z;
Y2(:,odd) = S;
Y2(:,even) = T;
end
Y2(bus+2,:) = cus_node;
YY4 = Y2;
function crossover1(n,i,a,sizea,child1)
for k=1:sizea
if child1(n) == a(k)
if child1(k) == 0
child1(k) = a(i);
break;
else
crossover1(k,i,a,sizea,child1)
end
end
end
end
function crossover2(n,i,b,sizeb,child2)
for k=1:sizeb
if child2(n) == b(k)
if child2(k) == 0
child2(k) = b(i);
break;
else
crossover2(k,i,b,sizeb,child2)
end
end
end
end
2 个评论
Debadipto
2023-6-5
Could you please elaborate on the output you're intending to get? Wrapping the function inside a for loop should ideally give you multiple pairs of output. Maybe you can share your code snippet.
采纳的回答
Debadipto
2023-6-8
Hi Wan,
You can use the following script to generate multiple pair of chromosomes:
a = [1 3 4 6 7 10];
b = [2 3 7 4 6 10];
n = 4;
chromosomes = [];
for i = 1:4
chromosomes(:, :, i) = crossover(a, b);
end
disp(chromosomes)
function child= crossover(a, b)
% crossover function logic ...
end
Regards,
Debadipto Biswas
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Genetic Algorithm 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!