Index in position 2 exceeds array bounds (must not exceed 2). Error in fun1 (line 5)

9 views (last 30 days)
%%Minimze
function out =fun1(x)
A1=x(:,1)
A2=x(:,2)
A3=x(:,3)
%%Let's write the objective fucntion
fx=8.*A1+10.*A2+2.*A3;
%%% Now writing all inequality constraints here
g(:,1)=A1+3.*A2+2.*A3;
g(:,2)=-A1-5.*A2-A3;
%%DEFINE PENALTY TERM
pp=10^9;
for i=1:size(g,1)
for j=1:size(g,2)
if g(i,j)>0
penalty(i,j)=pp.*g(i,j);
else
penalty(i,j)=0;
end
end
end
%%% COMPUTE OBJECTIVE FUNCTION
out=fx+sum(penalty,2);
format short
clear all
clc
%% INITIALIZING THE PARAMETERS
fun=@fun1;
N=300;
D=2;
lb=[-8 -8 -8];
ub=[10 10 10];
itermax=100;
%%GENERATING THE INITIAL POPULATION
for i=1:N
for j=1:D
pos(i,j)=lb(j)+rand*(ub(j)-lb(j));
end
end
%%EVALUATING OBJECTIVE FUNCTION
fx=fun(pos);
%%INITIALIZE gBEST
[fminvalue,ind]=min(fx);
gbest=pos(ind,:);
gbest
%%GWO MAIN LOOP WILL START NOW
iter=1;
while iter<=itermax
Fgbest=fminvalue;
a=2-2*(iter/itermax)
for i=1:N
x=pos(i,:);
pos1=pos;
A1=2.*a.*rand(1,D)-a;
C1=2.*rand(1,D);
%% Now let's calculate ALPHA Value i.e., FIRST BEST
[alpha,alphaind]=min(fx);
alphapos=pos1(alphaind,:);
Dalpha=abs(C1.*alphapos-x);
x1=alphapos-A1.*Dalpha;
pos1(alphaind,:)=[];
fx1=fun(pos1);
%% Now let's calculate BETA Value i.e., SECOND BEST
[bet,betind]=min(fx1);
betpos=pos1(betind,:);
A2=2.*a.*rand(1,D)-a;
C2=2.*rand(1,D);
Dbet=abs(C2.*betpos-x);
x2=betpos-A2.*Dbet;
%%FINDING DELTA POSITION i.e., THIRD BEST
[delta,deltaind]=min(fx1);
deltapos=pos1(deltaind,:);
A3=2.*a.*rand(1,D)-a;
C3=2.*rand(1,D);
Ddelta=abs(C3.*deltapos-x);
x3=deltapos-A3.*Ddelta;
xnew=(x1+x2+x3)./3
%%%CHECK THE BOUNDARIES
xnew=max(xnew,lb);
xnew=min(xnew,ub);
fnew=fun(xnew);
%%%GREEDY SELECTION
if fnew<fx(i)
pos(i,:)=xnew;
fx(i,:)=fnew;
end
end
%%UPDATE GBEST (DESTINATION)
[fmin,find]=min(fx);
if fmin<Fgbest
Fgbest=fmin;
gbest=pos(find,:);
end
%%%%MEMORIZE THE BEST SOLUTION
[optval,optind]=min(fx);
BestFx(iter)=optval;
BestX(iter,:)=pos(optind,:);
%%%SHOW ITERATION INFORMATION
iter=iter+1
end

Answers (1)

Sargondjani
Sargondjani on 20 Sep 2021
You calculate:
for i=1:N
for j=1:D
pos(i,j)=lb(j)+rand*(ub(j)-lb(j));
end
end
with D= 2, so pos is an N by D matrix. However your input argument in fun1 requires 3 columns, since you define A3=x(:,3).
With D=3 your problem should be fixed.

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by