jacobi method using one for loop

7 次查看(过去 30 天)
Isaac Al-rai
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 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by