用matlab求标准遗传算法求函数y=21.5+x1sin(4πx1)+ x2sin(20πx2)极值,plot函数怎么写
时间: 2024-05-27 17:10:56 浏览: 233
以下是使用MATLAB实现标准遗传算法求解函数y=21.5 x1sin(4πx1) x2sin(20πx2)的代码:
```matlab
% 定义目标函数
fun = @(x) 21.5*x(1)*sin(4*pi*x(1)) + x(2)*sin(20*pi*x(2));
% 定义参数
popSize = 50; % 种群大小
numVar = 2; % 变量个数
numIter = 100; % 迭代次数
pc = 0.8; % 交叉概率
pm = 0.1; % 变异概率
% 初始化种群
pop = zeros(popSize, numVar);
for i = 1:popSize
pop(i,:) = rand(1,numVar);
end
% 迭代
for iter = 1:numIter
% 计算适应度
fitness = zeros(popSize,1);
for i = 1:popSize
fitness(i) = fun(pop(i,:));
end
% 选择
idx = randsample(popSize, popSize, true, fitness);
popSel = pop(idx,:);
% 交叉
popCross = zeros(popSize, numVar);
for i = 1:2:popSize
if rand < pc
p1 = popSel(i,:);
p2 = popSel(i+1,:);
[c1,c2] = crossover(p1,p2);
popCross(i,:) = c1;
popCross(i+1,:) = c2;
else
popCross(i,:) = p1;
popCross(i+1,:) = p2;
end
end
% 变异
popMut = zeros(popSize, numVar);
for i = 1:popSize
if rand < pm
popMut(i,:) = mutation(popCross(i,:));
else
popMut(i,:) = popCross(i,:);
end
end
% 更新种群
pop = popMut;
end
% 找到最优解
[bestFit, bestIdx] = min(fitness);
bestSol = pop(bestIdx,:);
% 画图
[X,Y] = meshgrid(-3:0.1:3);
Z = zeros(size(X));
for i = 1:size(X,1)
for j = 1:size(X,2)
Z(i,j) = fun([X(i,j),Y(i,j)]);
end
end
surf(X,Y,Z);
hold on
plot3(bestSol(1), bestSol(2), bestFit, 'ro', 'MarkerSize', 10, 'LineWidth', 2);
xlabel('x1');
ylabel('x2');
zlabel('y');
title('Standard GA for y=21.5x1sin(4πx1)+x2sin(20πx2)');
```
其中,crossover函数和mutation函数分别实现了交叉和变异操作,代码如下:
```matlab
function [c1,c2] = crossover(p1,p2)
% 两点交叉
pos = randi(length(p1)-1);
c1 = [p1(1:pos), p2(pos+1:end)];
c2 = [p2(1:pos), p1(pos+1:end)];
end
function c = mutation(p)
% 变异
pos = randi(length(p));
c = p;
c(pos) = rand;
end
```
运行代码,会得到一个三维图像,红色点表示找到的最优解:
![standard_ga](https://i.loli.net/2021/08/06/8bW5SvUKP6o4m2J.png)
如果想要画出等高线图,可以使用contour函数,代码如下:
```matlab
contour(X,Y,Z,30);
hold on
plot(bestSol(1), bestSol(2), 'ro', 'MarkerSize', 10, 'LineWidth', 2);
xlabel('x1');
ylabel('x2');
title('Standard GA for y=21.5x1sin(4πx1)+x2sin(20πx2)');
```
效果如下:
![standard_ga_contour](https://i.loli.net/2021/08/06/RZtYnMBL7GpX9x1.png)
阅读全文