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

2022-05-28 15:04:13 浏览数 (1)

代码语言:javascript复制

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('搜索次数:%dn',T)

0 人点赞