jacobi method using one for loop

조회 수: 3 (최근 30일)
Isaac Al-rai
Isaac Al-rai 2018년 2월 17일
편집: Isaac Al-rai 2018년 2월 17일
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?

답변 (1개)

Isaac Al-rai
Isaac Al-rai 2018년 2월 17일
편집: Isaac Al-rai 2018년 2월 17일
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

카테고리

Help CenterFile Exchange에서 Elementary Math에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by