clc;
clear;
f = inline('2.4-(x.^4 + 3*y.^4 - 0.2*cos(3*pi*x) - 0.4*cos(4*pi*y) + 0.6)');
x = -1:0.001:1;
y = -1:0.001:1;
[X,Y] = meshgrid(x,y);
F = f(X,Y);
figure(1);
mesh(X,Y,F);
xlabel('横坐标x'); ylabel('纵坐标y'); zlabel('空间坐标z');
hold on;
lower_x = -1;
upper_x = 1;
lower_y = -1;
upper_y = 1;
ant = 80;
times = 30;
rou = 0.9;
p0 = 0.2;
ant_x = zeros(1,ant);
ant_y = zeros(1,ant);
tau = zeros(1,ant);
Macro = zeros(1,ant);
for i=1:ant
ant_x(i) = (upper_x-lower_x)*rand() + lower_x;
ant_y(i) = (upper_y-lower_y)*rand() + lower_y;
tau(i) = f(ant_x(i),ant_y(i));
plot3(ant_x(i),ant_y(i),tau(i),'k*');
hold on;
Macro = zeros(1,ant);
end
fprintf('蚁群搜索开始(找最大值):\n');
T = 1;
tau_best = zeros(1,times);
p = zeros(1,ant);
while T < times
lamda = 1/T;
[tau_best(T),bestindex] = max(tau);
if T >= 3 && abs((tau_best(T) - tau_best(T-2))) < 0.000001
fprintf('精度足够高,提前结束!\n');
plot3(ant_x(bestindex), ant_y(bestindex), f(ant_x(bestindex),ant_y(bestindex)), 'b*');
break;
end
plot3(ant_x(bestindex), ant_y(bestindex), f(ant_x(bestindex),ant_y(bestindex)), 'r*');
hold on;
for i = 1:ant
p(i) = (tau(bestindex) - tau(i))/tau(bestindex);
end
for i = 1:ant
if p(i) < p0
tempx = ant_x(i) + (2*rand-1)*lamda;
tempy = ant_y(i) + (2*rand-1)*lamda;
else
tempx = ant_x(i) + (upper_x-lower_x)*(rand-0.5);
tempy = ant_y(i) + (upper_y-lower_y)*(rand-0.5);
end
if tempx < lower_x
tempx = lower_x;
end
if tempx > upper_x
tempx = upper_x;
end
if tempy < lower_y
tempy = lower_y;
end
if tempy > upper_y
tempy = upper_y;
end
if f(tempx,tempy) > tau(i)
ant_x(i) = tempx;
ant_y(i) = tempy;
Macro(i) = f(tempx,tempy);
end
end
for i = 1:ant
tau(i) = (1-rou)*tau(i) + Macro(i);
end
T = T + 1;
end
hold off;
fprintf('蚁群搜索到的最大值点:(%.5f,%.5f,%.5f)\n',...
ant_x(bestindex), ant_y(bestindex), f(ant_x(bestindex),ant_y(bestindex)));
fprintf('搜索次数:%d\n',T)
本文分享自 图像处理与模式识别研究所 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有