Index exceeds the number of array elements (1).

1 次查看(过去 30 天)
clear
close all
% Problem Statement
Npar = 17;
VarLow=0.1;
VarHigh = 35;
%BBBC parameters
N=50; %number of candidates
MaxIter=100; %number of iterations
% initialize a random value as best value
XBest = rand(1,Npar).* (VarHigh - VarLow) + VarLow;
FBest=fitnessFunc(XBest);
GB=FBest;
t = cputime;
%intialize solutions and memory
X = zeros(N, Npar);
F = zeros(N, 1);
for ii = 1:N
X(ii,:) = rand(1,Npar).* (VarHigh - VarLow) + VarLow;
% calculate the fitness of solutions
F(ii) = fitnessFunc(X(ii,:));
end
%Main Loop
for it=1:MaxIter
%Find the centre of mass
%-----------------------
%numerator term
num=zeros(1,Npar);
for ii=1:N
for jj=1:Npar
num(jj)=num(jj)+(X(ii,jj)/F(ii));
end
end
%denominator term
den=sum(1./F);
%centre of mass
Xc=num/den;
%generate new solutions
%----------------------
for ii=1:N
%new solution from centre of mass
for jj=2:Npar
New=X(ii,:);
New(jj)=Xc(jj)+((VarHigh(jj)*rand)/it^2);
end
%boundary constraints
New=limiter(New,VarHigh,VarLow);
%new fitness
newFit=fitnessFunc(New);
%check whether the solution is better than previous solution
if newFit<F(ii)
X(ii,:)=New;
F(ii)=newFit;
if F(ii)<FBest
XBest=X(ii,:);
FBest=F(ii);
end
end
end
% store the best value in each iteration
GB=[GB FBest];
end
%Main Loop
for it=1:MaxIter
%Find the centre of mass
%-----------------------
%numerator term
num=zeros(1,Npar);
for ii=1:N
for jj=1:Npar
num(jj)=num(jj)+(X(ii,jj)/F(ii));
end
end
%denominator term
den=sum(1./F);
%centre of mass
Xc=num/den;
%generate new solutions
%----------------------
for ii=1:N
%new solution from centre of mass
for jj=2:Npar
New=X(ii,:);
New(jj)=Xc(jj)+((VarHigh(jj)*rand)/it^2);
end
Hi please can someone help me the code runs perfectly on my computer, but when transferred to another and ran, it gives the error message (index exceeds the number of array elements (1))? And error in this line New(jj)=Xc(jj)+((VarHigh(jj)*rand)/it^2);

回答(1 个)

Alex Mcaulley
Alex Mcaulley 2020-2-19
VarHigh is a constant and you are using it as an array...
VarHigh(2) %Throws an error

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by