Index exceeds the number of array elements. Index must not exceed 2.

6 views (last 30 days)
I am tryin to solve Laplace's equation using the finite difference method using the code below I get the following error, "Index exceeds the number of array elements. Index must not exceed 2.". Any help on how to combat this error would be much appreciated.
function u = Laplace_annular(r1,r2)
% Specifying parameters
Sec = 40; % Number of section iterations
Ang = 100; % Number of angle iterations
dtheta= 2*pi/Ang; % Number of angle steps (radians)
dr = (r1 - r2)/Ang;
r = r1:dr:r2;
theta = 0:dtheta:2*pi;
[r,theta] = meshgrid(r,theta);
% Initialising solution array
u = zeros(Ang+1,Sec+1);
u_0 = zeros(Ang+1,Sec+1);
u(1,:) = u(1,:)+1;
u(2,:) = u(2,:)+0;
% Solving equation
beta = dr^2/dtheta^2;
n = 1;
k = 0;
while k == 0
u_0 = u;
k = 1;
for i = 2:80
for j = 2:40
r(j) = 1 + (j-1)*dr;
theta(i) = dtheta/2 + (i-1)*dtheta;
ua1 = ((r(j) + r(j+1))/2)*u_0(i,j+1) + ((r(j)+r(j-1))/2)*u_0(i,j-1);
ua2 = beta*u_0(i+1,j) + beta*u_0(i-1,j);
ua = ua1 + ua2;
ub = ((r(j)+r(j+1))/2)+((r(j)+r(j-1))/2)+2*beta;
u(i,j) = ua/ub;
if abs(u(i,j)-u_0(i,j))>(10^-5)
k=0;
end
end
end
n=n+1;
end
end

Answers (1)

Torsten
Torsten on 31 Aug 2022
dr = (r1 - r2)/Ang;
implies r1 > r2
r = r1:dr:r2;
implies r2 > r1
So what is correct ?
  3 Comments
Torsten
Torsten on 1 Sep 2022
Then you know what you have to do ?
r = r2:dr:r1
instead of
r = r1:dr:r2;
And most probably you mean
dr = (r1 - r2)/Sec;
instead of
dr = (r1 - r2)/Ang;
?
And in the looping part
for i = 2:100
instead of
for i = 2:80
?

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!