matlab代码----背包问题(遗传算法解决)

缺少main.m

GA_beibao_tubian.m

function Population1=GA_tubian(Population,pe_tubian)
%遗传算法突变算子
%pe为突变概率
Population1=Population;
n=length(Population(:,1));
m=length(Population(1,:));
for i=1:n
    for j=1:m
        test=rand;
        if test<pe_tubian
            Population1(i,j)=1-Population1(i,j);
        end
    end
end



GA_beibao_initial.m

function Population=GA_Initial(n,P)
%n为染色体长度,即所供选择的物品总数
%P为初始种群大小
for i=1:P
    for j=1:n
        temp=rands(1,1);
        if temp>0
            Population(i,j)=1;
        else 
            Population(i,j)=0;
        end
    end
end

        
    


GA_beibao_fitnessvalue.m

function fitnessvalue=GA_fitnessvalue(x,p,w0,w)
%使用惩罚法计算适应度值 
%x为染色体
%p为背包问题中每个被选物体的价值
%w0为背包问题中背包总容积
%w为背包问题中每个被选物品的容积
l=length(x);
for i=1:l
    a(i)=p(i).*x(i);
end
f=sum(a);
b=min(w0,abs(sum(w)-w0));
for i=1:l
    wx(i)=w(i).*x(i);
end
if abs(sum(wx)-w0)>b*0.99
    p=0.99;
else
    p=abs(sum(wx)-w0)/b;
end
fitnessvalue=f*(1-p)*(1-p)*(1-p);

GA_beibao_exchange.m

function Population1=GA_exchange(Population,pc)
%遗传算法交换算子
%pc为交换概率
Population1=Population;
POP=[];
n=length(Population(:,1));
%k=floor(n*pc);  %用于交换的染色体数目
%采用单点交换算子
j=1;
l=length(Population(1,:));
for i=1:n
    test(i)=rand;
    if test(i)<pc
        for z=1:l
            POP(j,z)=Population(i,z);
        end
        POP(j,l+1)=i;
        p(j)=randint(1,1,[1 l-1]);
        j=j+1;
    end
end
k0=j-1;
k=floor(k0/2);
if k>=1
    for m=1:k
        for t=p(2*m-1)+1:l
        s=POP(2*m-1,t);
        POP(2*m-1,t)=POP(2*m,t);
        POP(2*m,t)=s;
        end
    end
    for m=1:k0
        for i=1:l
        Population1(POP(m,l+1),i)=POP(m,i);
        end
    end
end
    
        
        
    
    

GA_beibao_copy.m

function Population1=GA_copy(Population,p,w0,w)
%复制算子
%Population为种群
n=length(Population(:,1));
fvalue=zeros(1,n);
for i=1:n
    fvalue(i)=GA_beibao_fitnessvalue(Population(i,:),p,w0,w);
end
fval=fvalue/sum(fvalue);
F(1)=0;
for j=1:n
    F(j+1)=0;
    for k=1:j
        F(j+1)=F(j+1)+fval(k);
    end
end
for i=1:n
    test=rand;
    for j=1:n
        if((test>=F(j))&&(test<F(j+1)))
            Population1(i,:)=Population(j,:);
        end
    end
end
        
        
        

你可能感兴趣的:(matlab)