Index out of bounds Error
Show older comments
Hey I have the following code which I am unable to compile as I'm getting out of bound error.
in the line
du=abs(ukp1(:,:)-u(:,:));
clear all
clc
L=5;
H=5;
delx=0.2;
dely=0.2;
ERRORMAX=0.01;
W=input(' Enter the relaxation parameter \omega < 2 ');
h=zeros(L/delx+1,H/dely+1);
G=h;
G(1,[1:5])=0;
G(1,[6:26])=100;
G([1:15],26)=100;
G([16:26],26)=0;
G(26,:)=0;
G(:,1)=0;
u(1,[1:5])=0;
u(1,[6:26])=100;
u([1:15],26)=100;
u([16:26],26)=0;
u(26,:)=0;
u(:,1)=0;
u([2:L/delx-1],[2:H/dely-1])=input('Enter the guess solution :' );
beta=delx/dely;
A=W;
B=-2*(1+beta^2);
C=A;
error=1;
while error>ERRORMAX
for i=2:L/delx
for j=H:dely
D(i,j)=-(1-W)*(2*(1+beta^2))*u(i,j)-(W*beta^2*(u(i+1,j)+u(i-1,j)));
h(i,j)=C/(B-A*h(i,j-1));
G(i,j)=(D(i,j)-A*G(i,j-1))/(B-A*h(i,j-1));
end
for k=H/dely:-1:2
ukp1(i,k-1)=-h(i,k-1)*u(i,k)+G(i,k-1);
end
end
du=abs(ukp1(:,:)-u(:,:));
Error=sum(du);
error=sum(Error);
disp(ukp1(:,[1 6 11 16 21 26]));
end
2 Comments
Walter Roberson
on 11 Oct 2015
If you had said which line, I might have tried to answer. But I'm going to bed instead.
pepsodent
on 11 Oct 2015
Answers (1)
Walter Roberson
on 11 Oct 2015
You are not getting an "out of bound" error, you are getting a "matrix dimension must agree" error on the subtraction.
>> size(ukp1)
ans =
25 24
>> size(u)
ans =
26 26
You initialize u([16:26],26)=0; so u is going to be at least 26 by 26, but your computation for ukp1 has k=H/dely to start and that is 5/0.2 which is 25 . And then you subtract 1 from k when using it as the index into ukp1, so your maximum index based on that is going to be 24. Therefore you are not creating ukp1 as the same size as u, and you cannot subtract the two matrices.
2 Comments
pepsodent
on 12 Oct 2015
Walter Roberson
on 12 Oct 2015
It can be fixed in the "Rewrite the program from scratch" sense. Except the second time write it with comments. And with the matrix bounds calculated and placed into variables instead of being used as expressions like L/delx all over the place. And you should add code that cross-checks the bounds and gives an error message if they are not consistent.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!