标签:io os ar for on cti line new size
%% 遗传算法
clc;
clear all;
close all;
%% 绘图
x = -1:0.01:2;
y = x .* sin(10 * pi.*x) + 2.0;
plot(x,y,‘b-‘,‘linewidth‘,2);
hold on
%% 初始化
xmin = -1;%参数范围
xmax = 2;%参数范围
gen_max = 200;%最大迭代次数
pop_size = 100;%种群规模
best_fit = -inf;%最佳适应度
string = 10;%基因
bval = round(rand(pop_size,string));%序列
pcross = 0.8;%交叉概率,一般取0.5--0.85之间较好(默认0.8)
pmutation = 0.1;%- 初始变异概率,一般取0.05-0.2之间较好(默认0.1)
pinversion = 0.2;% 倒位概率,一般取0.05-0.3之间较好(默认0.2)
%% j计算适应度 fitvalue 和累积概率
for ii =1:gen_max
for i = 1:pop_size
x =0;
for j = 1:string
x = x + bval(i,string - j + 1)*2^(j-1);
end
x1 = (xmax - xmin)*x/(2^string-1) + xmin;
obj(i) = fit_fun(x1);
xx(i) = x1;
end
func = obj;
p = func./sum(func);
q = cumsum(p);
[fmax,index] = max(func);
if fmax >best_fit
best_fit = fmax;
bvall = bval(index,:);
optxx = xx(index);
end
Bfit(ii) = best_fit;
%轮盘赌选择
for i =1:(pop_size-1)
r = rand;
tmp = find(r<q);
newbval(i,:) = bval(tmp(1),:);
end
newbval(pop_size,:) = bvall;
bval = newbval;
%单点交叉
for i = 1:2:(pop_size -1)
cc = rand;
if cc < pcross
point = ceil(rand*(string-1));
ch = bval(i,:);
bval(i,point+1:string)=bval(i+1,point+1:string);
bval(i+1,point+1:string)=ch(1,point+1:string);
end
end
bval(pop_size,:)=bvall;%最优保留
%位点变异
mm=rand(pop_size,string);
mm(pop_size,:)=zeros(1,string);%最后一行不变异,强制赋0
bval=1-mm;
end
function fit = fit_fun(x)
fit = x * sin(10 * pi*x) + 2.0;
end
标签:io os ar for on cti line new size
原文地址:http://www.cnblogs.com/Kermit-Li/p/4050729.html