matlab编程如何把目标函数和算法联系起来,我想换一个目标函数

BSBTWWW 2020-05-18 02:50:29
function [best,fmin,N_iter]=fpa_demo(para)
%参数
if nargin<1,
para=[20 0.8];
end

n=para(1); % 规模
p=para(2); % 概率

% 迭代参数
N_iter=500; % 迭代总次数

%搜索变量
d=3;
Lb=-2*ones(1,d);
Ub=2*ones(1,d);

% 初始化群体
for i=1:n,
Sol(i,:)=Lb+(Ub-Lb).*rand(1,d);
Fitness(i)=Fun(Sol(i,:));
end

%找到当前最好
[fmin,I]=min(Fitness);
best=Sol(I,:);
S=Sol;

%开始迭代
for t=1:N_iter,
% Loop over all bats/solutions
for i=1:n,
% Pollens are carried by insects and thus can move in
% large scale, large distance.
% This L should replace by Levy flights
% Formula: x_i^{t+1}=x_i^t+ L (x_i^t-gbest)
if rand>p,
%% L=rand;
L=Levy(d);
dS=L.*(Sol(i,:)-best);
S(i,:)=Sol(i,:)+dS;

% 检查界限
S(i,:)=simplebounds(S(i,:),Lb,Ub);

% If not, then local pollenation of neighbor flowers
else
epsilon=rand;
% 随机产生花朵
JK=randperm(n);
% As they are random, the first two entries also random
% If the flower are the same or similar species, then
% they can be pollenated, otherwise, no action.
% Formula: x_i^{t+1}+epsilon*(x_j^t-x_k^t)
S(i,:)=S(i,:)+epsilon*(Sol(JK(1),:)-Sol(JK(2),:));
% Check if the simple limits/bounds are OK
S(i,:)=simplebounds(S(i,:),Lb,Ub);
end

%评估新的
Fnew=Fun(S(i,:));
% 如果是更好的方案,就更新
if (Fnew<=Fitness(i)),
Sol(i,:)=S(i,:);
Fitness(i)=Fnew;
end

% 更新当前最佳
if Fnew<=fmin,
best=S(i,:) ;
fmin=Fnew ;
end
end
% 每100次迭代结果
if round(t/100)==t/100,
best;
fmin;
end

end

%输出
disp(['Total number of evaluations: ',num2str(N_iter*n)]);
disp(['Best solution=',num2str(best),' fmin=',num2str(fmin)]);


% 简单的约束
function s=simplebounds(s,Lb,Ub)
% 设定下限
ns_tmp=s;
I=ns_tmp<Lb;
ns_tmp(I)=Lb(I);

% 设定上限
J=ns_tmp>Ub;
ns_tmp(J)=Ub(J);
% Update this new move
s=ns_tmp;


% levy 飞行
function L=Levy(d)
beta=3/2;
sigma=(gamma(1+beta)*sin(pi*beta/2)/(gamma((1+beta)/2)*beta*2^((beta-1)/2)))^(1/beta);
u=randn(1,d)*sigma;
v=randn(1,d);
step=u./abs(v).^(1/beta);
L=0.01*step;

% Objective function and here we used Rosenbrock's 3D function
function z=Fun(u)
z=(1-u(1))^2+100*(u(2)-u(1)^2)^2+100*(u(3)-u(2)^2)^2;
...全文
271 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

24,855

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧