2019-04-23 17:23

# MATLAB报错未定义函数或变量怎么破啊？附代码

%%-----------------------------------------------------------------------------------------------------------------
% fobj 评价函数

% dim 变量的个数

% Max_iteration 最大迭代次数

% SearchAgents_no 种群规模

% lb=[lb1,lb2,...,lbn] lbn 是变量 n 的下界

% ub=[ub1,ub2,...,ubn] ubn 是变量 n 的上界

%%-----------------------------------------------------------------------------------------------------------------

% 位置更新函数

[Alpha_score,Alpha_pos,Convergence_curve]=GWO(SearchAgents_no,Max_iter,lb,ub,dim,fobj)

% 初始化alpha, beta,和delta_pos
Alpha_pos=zeros(1,dim);
Alpha_score=inf;

Beta_pos=zeros(1,dim);
Beta_score=inf;

Delta_pos=zeros(1,dim);
Delta_score=inf;

%初始化灰狼个体的位置

Positions=initialization(SearchAgents_no,dim,ub,lb);

Convergence_curve=zeros(1,Max_iter);

l=0; % 循环计数

% 主循环

while l<Max_iter
for i=1:size(Positions,1)

``````    %  边界控制

Flag4ub=Positions(i,:)>ub;
Flag4lb=Positions(i,:)<lb;
Positions(i,:)=(Positions(i,:).*(~(Flag4ub+Flag4lb)))+ub.*Flag4ub+lb.*Flag4lb;

%  计算评价函数

fitness=fobj(Positions(i,:));
%  更新 Alpha, Beta  和 Delta
if fitness<Alpha_score
Alpha_score=fitness; %  更新  alpha
Alpha_pos=Positions(i,:);
end

if fitness>Alpha_score && fitness<Beta_score
Beta_score=fitness; %  更新 beta
Beta_pos=Positions(i,:);
end

if fitness>Alpha_score && fitness>Beta_score && fitness<Delta_score
Delta_score=fitness; %  更新delta
Delta_pos=Positions(i,:);
end
end

a=2-l*((2)/Max_iter); %  线性下降从 2到0
``````

% 更新灰狼个体的位置

`````` for i=1:size(Positions,1)
for j=1:size(Positions,2)

r1=rand(); % r1  是 0 到 1 之间的随机数

r2=rand(); % r2 是 0 到 1 之间的随机数

A1=2*a*r1-a;
C1=2*r2;

D_alpha=abs(C1*Alpha_pos(j)-Positions(i,j));
X1=Alpha_pos(j)-A1*D_alpha;

r1=rand();
r2=rand();

A2=2*a*r1-a;
C2=2*r2;

D_beta=abs(C2*Beta_pos(j)-Positions(i,j));
X2=Beta_pos(j)-A2*D_beta;

r1=rand();
r2=rand();

A3=2*a*r1-a;
C3=2*r2;

D_delta=abs(C3*Delta_pos(j)-Positions(i,j));
X3=Delta_pos(j)-A3*D_delta;

Positions(i,j)=(X1+X2+X3)/3;

end
end
l=l+1;
Convergence_curve(l)=Alpha_score;
``````

end