jacobi method using one for loop

3 views (last 30 days)
Isaac Al-rai
Isaac Al-rai on 17 Feb 2018
Edited: Isaac Al-rai on 17 Feb 2018
I have a code written that will use jacobi method to solve a problem but in my numerical methods class I need to be able to perfrom this function in one loop. Here is my current code:
if true
% code
function X=jacobi(A,B,P,delta,max1)
N = length(B);
for k=1:max1
for j=1:N
X(j)=(B(j)-A(j,[1:j-1,j+1:N])*P([1:j-1,j+1:N]))/A(j,j);
end
err=abs(norm(X'-P));
relerr=err/(norm(X)+eps);
P=X';
if (err<delta)||(relerr<delta)
break
end
end
X=X';
end
end
And this seems to work. It defines X(j) and spits out values from 1 to the length of B(100). Now I need to find a way to make this run using only ONE for loop. so I need to probably get rid of the j indices and replace it with k. Anyone know how I can make this work?

Answers (1)

Isaac Al-rai
Isaac Al-rai on 17 Feb 2018
Edited: Isaac Al-rai on 17 Feb 2018
I first tried to replace the second for loop with
if true
% code
j=eye(100)
end
And adjusted my code to look like this
if true
% code
function X=jacobian(A,B,P,delta,max1)
N = length(B);
for k=1:max1
j=eye(100)
X(1:j)=(B(1:j)-A(1:j,[1:j-1,j+1:N])*P([1:j-1,j+1:N]))/A(1:j,1:j);
end
err=abs(norm(X'-P));
relerr=err/(norm(X)+eps);
P=X';
if (err<delta)||(relerr<delta)
RETURN
end
X=X';
end
end
And I am getting an answer but not sure if it is right. It is spitting out one answer in comparison to my previous code which would spit out a matrix

Categories

Find more on Elementary Math 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!