麻雀搜索算法(SSA)求解二元一次函数(附完整代码)

博客给出了目标函数、bound条件及主函数的代码。目标函数通过特定公式计算,bound条件用于处理边界情况,主函数得出最小值结果并提及结果图。涉及matlab等语言及算法相关内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目标函数:

function z =fun( x,y )
z=-20*exp(-0.2*sqrt(0.5*(x.^2+y.^2)))-exp(0.5*(cos(2*pi*x)+cos(2*pi*y)))+20+exp(1);
end

bound条件:

function s = Bounds( s, Lb, Ub)
  temp = s;
  I = temp < Lb;
  temp(I) = Lb(I);
  % Apply the upper bound vector 下边界
  J = temp > Ub;
  temp(J) = Ub(J);
  % Update this new move 
  s = temp;
end

主函数:

%% 麻雀搜素算法求解二元一次函数
%% 多图警告
%% 1 清楚变量
clc
close all
clear

%% 2 绘制函数仿真图(根据网格图绘制等高线图meshc)

[x,y]=meshgrid(-32:0.1:32);
% [x,y]=meshgrid(-65:0.1:65);
figure
subplot(3,2,1)
% figure(1)
meshc(x,y,fun(x,y));
title('函数仿真图')
xlabel('x','fontname','Microsoft YaHei');
ylabel('y','fontname','Microsoft YaHei');
zlabel('z','fontname','Microsoft YaHei');
box on
grid on
%% 3 初始化种群参数
% 最大迭代次数
MaxIteration =60;
% 种群数量
Sizepop =30;
% 生产麻雀占比
rPercent = 0.2;
% 生产麻雀数量
rNum = round( Sizepop * rPercent );
% 设置边界
d=20;
c=-20;
% d=2;
% c=-2;
dim=2;
ub= d.*ones( 1,dim );  
lb= c.*ones( 1,dim );    
%% 4 种群初始化
for i = 1:Sizepop
    Position( i, : ) = c + (d - c) .* rand( 1, dim );
    fitness( i ) = fun(Position(i,1),Position(i,2));
end
% 预存变量-麻雀位置序列
Position1=zeros(Sizepop,1);
for i=1:Sizepop
    Position1(i,1)=i;
end
% 预存变量 麻雀位置序列
bestscore=zeros(MaxIteration,1);
for i=1:MaxIteration
    bestscore(i,1)=i;
end
%% 5绘制初始种群适应度函数值的图像
% figure(2)
subplot(3,2,2)
plot(Position1,fitness,'r-*',Position1,fitness);
xlabel('初始种群序列','fontname','Microsoft YaHei');
ylabel('初始种群适应度值','fontname','Microsoft YaHei');
title('初始种群适应度值分布','fontname','Microsoft YaHei UI');
% 个体最优值
pFit = fitness;        
% pFit个体最优值对应的最佳位置
pX = Position;
% fMin表示全局最优适应度值
[ fMin, bestI ] = min( fitness ); 
% 全局最优适应度值所对应的最佳位置
bestX = Position( bestI, : );             

%% 6 主循环
for t = 1 : MaxIteration
    % 适应度值排序
    [ ~, sortIndex ] = sort( fitness  );
    % 记录麻雀最差个体 即适应度值最大
    [fmax,B]=max(fitness);
    worse= Position(B,:);
    r2=rand(1);
    if(r2<0.8)
        % 生产者麻雀位置更新
        for i = 1 : rNum
            r1=rand(1);
            Position( sortIndex( i ), : ) = pX( sortIndex( i ), : )*exp(-(i)/(r1*MaxIteration));
            Position( sortIndex( i ), : ) = Bounds( Position( sortIndex( i ), : ), lb, ub );
            fitness( sortIndex( i ) ) = fun(Position(sortIndex( i ),1),Position(sortIndex( i ),2));
        end
    else
        for i = 1 : rNum
            Position( sortIndex( i ), : ) = pX( sortIndex( i ), : )+randn(1)*ones(1,dim);
            Position( sortIndex( i ), : ) = Bounds( Position( sortIndex( i ), : ), lb, ub );
            fitness( sortIndex( i ) ) = fun(Position(sortIndex( i ),1),Position(sortIndex( i ),2));   
        end
    end
    
    % 记录最优位置和对应索引
    [ fMMin, bestII ] = min( fitness );      
    bestXX = Position( bestII, : );             

    for i = ( rNum + 1 ) : Sizepop
        % floor 负无穷四舍五入
        A=floor(rand(1,dim)*2)*2-1;
        if( i>(Sizepop/2))
            Position( sortIndex(i ), : )=randn(1)*exp((worse-pX( sortIndex( i ), : ))/(i)^2);
        else
            Position( sortIndex( i ), : )=bestXX+(abs(( pX( sortIndex( i ), : )-bestXX)))*(A'*(A*A')^(-1))*ones(1,dim);
        end
        Position( sortIndex( i ), : ) = Bounds( Position( sortIndex( i ), : ), lb, ub );        
        fitness( sortIndex( i ) ) = fun(Position(sortIndex( i ),1),Position(sortIndex( i ),2)); 
    end
    % 随机麻雀更新
    % randperm 生成随机整数
    c=randperm(numel(sortIndex));
    b=sortIndex(c(1:6));
    for j =  1  : length(b)
        if( pFit( sortIndex( b(j) ) )>(fMin) )
            Position( sortIndex( b(j) ), : )=bestX+(randn(1,dim)).*(abs(( pX( sortIndex( b(j) ), : ) -bestX)));
        else
            Position( sortIndex( b(j) ), : ) =pX( sortIndex( b(j) ), : )+(2*rand(1)-1)*(abs(pX( sortIndex( b(j) ), : )-worse))/ ( pFit( sortIndex( b(j) ) )-fmax+1e-50);
        end
        Position( sortIndex(b(j) ), : ) = Bounds( Position( sortIndex(  b(j) ), : ), lb, ub );
        fitness( sortIndex( b(j) ) ) = fun(Position(sortIndex( b(j) ),1),Position(sortIndex( b(j) ),2));
    end
    fitnesstable(t,:)=fitness;
    X(t,:,:)=Position;
    for i = 1 : Sizepop
        if ( fitness( i ) < pFit( i ) )
            pFit( i ) = fitness( i );
            pX( i, : ) = Position( i, : );
        end
        
        if( pFit( i ) < fMin )
            fMin= pFit( i );
            bestX = pX( i, : );
            
        end
    end
    
    best_ssa(t) = fMin;
    
end
%% 7 输出结果 并绘制仿真图
% figure(3)
subplot(3,2,3)
plot(bestscore,best_ssa,'LineWidth',1.5);
grid;
title('麻雀搜索算法收敛曲线图');
xlabel('迭代次数');
ylabel('适应度值');
% 输出最优值
disp('最小值为:')
min(fitness)
%% 8 种群分布图1
% figure(4)
subplot(3,2,4)
%创建随机初始化颜色矩阵
rgb=hsv(Sizepop);
[u,v]=meshgrid(-20:0.05:20);
contour(u,v,fun(u,v),300); 
hold on;
colorbar
xlabel('x');
ylabel('y');
for i=2:MaxIteration
    for j=1:Sizepop
        plot([X(i-1,j,1),X(i,j,1)],[X(i-1,j,2),X(i,j,2)],'*','color',rgb(j,:));
%         set(gca,'FontSize',10,'Fontname', 'Times New Roman');
    end
end
plot([0,0],[0,0],'rs','MarkerSize',15,'linewidth',1.0)
% set(gca,'FontSize',10,'Fontname', 'Times New Roman');
title('麻雀个体分布位置')
hold off
%% 9 种群分布图2
% figure(5)
subplot(3,2,[5,6])
rgb=hsv(Sizepop);
surf(u,v,fun(u,v)); 
hold on; 
alpha(0.4)
colorbar;
shading interp
xlabel('x');
ylabel('y');
zlabel('z')
for i=2:MaxIteration
    for j=1:Sizepop
        plot3([X(i-1,j,1),X(i,j,1)],[X(i-1,j,2),X(i,j,2)],[fitnesstable(i-1,j),fitnesstable(i,j)],'*','color',rgb(j,:));
%         set(gca,'FontSize',10,'Fontname', 'Times New Roman');
    end
end
% plot3([-0.0898,0.0898],[0.7126,-0.7126],[-1.031628,-1.031628],'kp','MarkerSize',20)
plot3([0,0],[0,0],[0,0],'rs','MarkerSize',15,'linewidth',1.0)
% set(gca,'FontSize',10,'Fontname', 'Times New Roman');
% axis([-50 50 -50 50 0 500]);
title('麻雀个体分布位置');
hold of

最小值:

ans =

     8.881784197001252e-16

结果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学习不好的电气仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值