# Error ' Index in position 2 exceeds array bounds'.how to correct this.

6 views (last 30 days)
susan sara on 6 Apr 2022
Edited: susan sara on 14 Jun 2022 at 13:22
When run it, shows
"Index in position 2 exceeds array bounds. Index
must not exceed 2.
Error in practice (line 20)
while(abs(a(k)-a(k-1))>=0.01) && abs(b(k)-b(k-1))>=0.01 && rms(abs(A(:,k)-A(:,k-1)))>=0.01"
clc;
clear;
a1=3;b1=8;
G=[50 ;100; 150; 175; 200 ;250 ;300];
Gbar=mean(G);
H=[20 ;15; 10 ;5; 1 ;0.5 ;0.1];
k=2;
a(2)=3;a(1)=1;
b(2)=8; b(1)=1;
A(:,k-1)=zeros(7,1);
A(:,k)=ones(7,1);
while(abs(a(k)-a(k-1))>=0.01) && abs(b(k)-b(k-1))>=0.01 && rms(abs(A(:,k)-A(:,k-1)))>=0.01
for i=1:length(G)
if G(i)>Gbar
x=[x i];
elseif G(i)<Gbar
y=[y i];
else
z=[z i];
end
end
for j=x(1):1:x(length(i))
A(j,k)=((H(j))/(a(k)))-1
for j=y(1):1:y(length(i))
A(j,k)=((H(j))/(b(k)))-1
end
if s>r
a(k+1)=sqrt((sum(a1.*H(x,:)))/(p1));
if (a1>=a(:,k+1)) && (a(:,k+1)>=b1)
a(k+1)=a1+(s/beta1);
else
end
k=k+1;
end

Geoff Hayes on 6 Apr 2022
Edited: Geoff Hayes on 6 Apr 2022
@susan sara - in your while loop conditions
while(abs(a(k)-a(k-1))>=0.01) && abs(b(k)-b(k-1))>=0.01 && rms(abs(A(:,k)-A(:,k-1)))>=0.01
you have
rms(abs(A(:,k)-A(:,k-1)))
. At the end of the loop you do
k=k+1;
. I don't see anywhere in the code where you update A for k+1 and so I suspect the error message is originating when indexing into A on the second iteration of the loop when k is 3. You may want to review this code
for j=x(1):1:x(length(i))
A(j,k)=((H(j))/(a(k)))-1
for j=y(1):1:y(length(i))
A(j,k)=((H(j))/(b(k)))-1
end
for j=z(1):1:z(length(i))
A(j,k)=G(j)
end
Is the above correct? Is there a missing end for the first for loop?