clc;
clear;close all;
c=[80 82 85 70 72 70 66 50 55 25 50 55 40 48 50 32 22 60 30 32 40 38 35 32 25 28 30 22 50 30 45 30 60 50 20 65 20 25 30 10 20 25 15 10 10 10 4 4 2 1];
value=[220 208 198 192 180 180 165 162 160 158 155 130 125 122 120 118 115 110 105 101 100 100 98 96 95 90 88 82 80 77 75 73 72 70 69 66 65 63 60 58 56 50 30 20 15 10 8 5 3 1];
g=value./c;%价值重量比
m1=1000;%总重量约束值
v = 2*rand(50,50)-1;
v=hardlim(v);
figure(1);
for i=1:50
for j=1:50
if v(i,j)==1
g1(i,j)=value(:,i)/c(:,j);
end
end
end
mesh(g1)
%贪婪算法修复解
v=greedy(v,c,g,m1);
[N,L] = size(v); ger = 200; pc = 0.5; pm = 0.01;%c=0;
sol1=1; vmfit = []; it = 1; vx = []; C = [];updatef=-10;
fit =v*value';
% Generations
t0 = clock;
hold on;
while it <= ger
% Selection 轮盘赌
for i=1:N
sp(i)=(fit(i)+3)/sum(fit+3);%
end
for i=2:N
sp(i)=sp(i-1)+sp(i);
end
for i=1:N
p=rand(1); sindex=1;
while p > sp(sindex)
sindex=sindex+1; %寻找要选择个体的位置
end
newv(i,:)=v(sindex,:);
end
for i=1:N
v(i,:)=newv(i,:);%用选择出的个体构成的种群替代旧的种群
end
% Crossver
for i=1:N
cindex(i)=i;
end
for i=1:N %产生要配对的父代的序号;经过N次顺序调换,将原有顺序打乱,使相邻两个个体作为交叉的父代
point=unidrnd(N-i+1);
temp=cindex(i);
cindex(i)=cindex(i+point-1);
cindex(i+point-1)=temp;
end
for i=1:2:N
p=rand(1);
if(p<pc)
point=unidrnd(L-1)+1;%1<point<L 产生交叉点
for j=point:(L-1) %交叉
ch=v(cindex(i),j);
v(cindex(i),j)=v(cindex(i+1),j); %cindex中相邻的两个为两个父代的序号
v(cindex(i+1),j)=ch;
end
end
end
% Mutation
M=rand(N,L)<=pm;%产生(N,L)维的01矩阵,为1的位置进行变异 找到小于0.01
v=v-2.*(v.*M)+M;%两个0-1矩阵相乘后M是1的地方V就不变,再乘以2.
v=greedy(v,c,g,m1);
fit = v*value';
[sol1,indb1] = max(fit); %每次迭代中最优目标函数值,包括位置
if updatef>=sol1
sol1=updatef;
v(indb1,:)=updatec;
end
updatef=sol1;
updatec=v(indb1,:);
[sol2,indb2] = min(fit);
v(indb2,:) = v(indb1,:);
fit = v*value';
media = mean(fit);%mean求平均值
it = it + 1;%迭代次数计算增加
figure(3);
plot(it,sol1,'r');
title('迭代走势图'); xlabel('Generations'); ylabel('best ');
end
T = etime(clock,t0); %F = flops - f0;
fx = sol1; P = v;
v_label=indb1;

 채택된 답변

pogleex
pogleex 2023년 5월 17일

0 개 추천

X = rand(n,m) 代表返回一个由均匀分布的随机数组成的 n×m 矩阵。如果想详细了解rand函数,可以在命令行界面内输入:help rand

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

태그

질문:

2023년 5월 17일

답변:

2023년 5월 17일

Community Treasure Hunt

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

Start Hunting!