clear;clc;
SearchAgents_no = 30;
Max_iter = 200;
dim = 2;
ub = 10 * ones(1, dim);
lb = -10 * ones(1, dim);
Alpha_pos = zeros(1, dim);
Alpha_score = inf;
Beta_pos = zeros(1, dim);
Beta_score = inf;
Delta_pos = zeros(1, dim);
Delta_score = inf;
Positions = rand(SearchAgents_no, dim) .* repmat(ub - lb, SearchAgents_no, 1) + repmat(lb, SearchAgents_no, 1);
Convergence_curve = zeros(1, Max_iter);
for l = 1 : Max_iter
for i = 1:SearchAgents_no
Flag4ub = Positions(i, :) > ub;
Flag4lb = Positions(i, :) < lb;
Positions(i, :) = (Positions(i, :) .* (~(Flag4ub + Flag4lb))) + ub .* Flag4ub + lb .* Flag4lb;
fitness = ObjFun(Positions(i, :));
if fitness < Alpha_score
Alpha_score = fitness;
Alpha_pos = Positions(i, :);
end
if fitness > Alpha_score && fitness < Beta_score
Beta_score = fitness;
Beta_pos = Positions(i, :);
end
if fitness > Alpha_score && fitness > Beta_score && fitness < Delta_score
Delta_score = fitness;
Delta_pos = Positions(i, :);
end
end
a = 2 - l * 2 / Max_iter;
for i = 1 : SearchAgents_no
for j = 1: dim
r1 = rand();
r2 = rand();
A1 = 2*a*r1 - a;
C1 = 2*r2;
D_alpha = abs(C1*Alpha_pos(j) - Positions(i, j));
X1 = Alpha_pos(j) - A1*D_alpha;
r1 = rand();
r2 = rand();
A2 = 2*a*r1 - a;
C2 = 2*r2;
D_beta = abs(C2*Beta_pos(j) - Positions(i, j));
X2 = Beta_pos(j) - A2*D_beta;
r1 = rand();
r2 = rand();
A3 = 2*a*r1 - a;
C3 = 2*r2;
D_delta = abs(C3*Delta_pos(j) - Positions(i, j));
X3 = Delta_pos(j) - A3*D_delta;
Positions(i, j) = (X1 + X2 + X3) / 3;
end
end
Convergence_curve(l) = Alpha_score;
end
disp(['最优值:' num2str(Alpha_pos)]);
disp(['最优值对应目标函数:' num2str(Convergence_curve(end))]);
subplot(1, 2, 1)
plot(Convergence_curve, 'LineWidth', 2);
xlabel('迭代次数');
ylabel('适应度值');
title('适应度曲线');
len = 50;
xRange = linspace(lb(1), ub(1), len);
yRange = linspace(lb(2), ub(2), len);
[xMap, yMap] = meshgrid(xRange, yRange);
zMap = zeros(len);
for i = 1 : len
for j = 1 : len
zMap(i, j) = ObjFun([xMap(i, j), yMap(i, j)]);
end
end
subplot(1, 2, 2)
surf(xRange, yRange, zMap);
view(-45, -45);
shading interp
hold on
plot3(Alpha_pos(1), Alpha_pos(2), ObjFun(Alpha_pos), 'o', 'MarkerFaceColor', 'r', 'MarkerSize', 10);
hold off
set(gcf, 'Position', [400, 200, 900, 400]);
function result = ObjFun(x)
dim=size(x,2);
result=-20*exp(-.2*sqrt(sum(x.^2)/dim))-exp(sum(cos(2*pi.*x))/dim)+20+exp(1);
end
__EOF__
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律