xover.m

来自「用MATLAB编写的遗传算法求解TSP问题的M文件」· M 代码 · 共 75 行

M
75
字号
function [son1,son2]=xover(parent1,parent2,N);
%function [son1,son2]=xover
%N=10;
x=randint(1,2,[1 N]);

%following two lines should be moved
%parent1=myrand(N);
%parent2=myrand(N);

if x(1)~=x(2)                                  %create two random number:x(1),x(2)
   if x(1)>x(2)
      temp=x(2);
      x(2)=x(1);
      x(1)=temp;
  end

 
temp=zeros(1,N+3);
    
for i=x(1):x(2)                                  %parent1 and parent2 exchange the part of each other
   temp(i)=parent2(i);
   parent2(i)=parent1(i);
   parent1(i)=temp(i);
end 

temp1=parent1;
temp2=parent2;
for i=x(1):x(2)
    temp1(i)=0;
    temp2(i)=0;
end

for  i=(x(1):x(2))
    for j=(1:N)
        if parent1(i)==temp1(j)
            flag=1;
            parent1(j)=parent2(i);
            while flag
                flag1=0;
                for k=(x(1):x(2))
                    if parent1(j)==parent1(k)
                        parent1(j)=parent2(k);
                        flag1=1;
                    end
                end
                flag=flag1;
            end
        end
    end
end

for  i=(x(1):x(2))
    for j=(1:N)
        if parent2(i)==temp2(j)
            flag=1;
            parent2(j)=parent1(i);
            while flag
                flag1=0;
                for k=(x(1):x(2))
                    if parent2(j)==parent2(k)
                        parent2(j)=parent1(k);
                        flag1=1;
                    end
                end
                flag=flag1;
            end
        end
    end
end

end

son1=parent1;
son2=parent2;

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?