前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >【Matlab代码】蚁群算法解得最大值

【Matlab代码】蚁群算法解得最大值

作者头像
裴来凡
发布于 2022-05-28 07:04:13
发布于 2022-05-28 07:04:13
85500
代码可运行
举报
运行总次数:0
代码可运行
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制

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)

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-04-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 图像处理与模式识别研究所 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档