Jacobi Method in calculating solution, number of iterations, and relative residue

조회 수: 17 (최근 30일)
N=50; % 50;
A=gallery('poisson',N);
n=size(A,1);
xs=ones(n,1);
b=A*xs(:);
MaxIter=10*n;
TOL=1.e-4;
t=cputime;
[x,info,relres]=myJacobi(A,b,MaxIter,TOL,n); % Jacobi example
mycput = cputime - t;
relerr = norm(xs-x)/norm(xs);
fprintf('size(A,1) = %d, relerr = %8.5e\n',n, relerr);
fprintf('time = %8.5e\n', mycput);
function [x,info,relres] = myJacobi(A,b,MaxIter,TOL,n)
%Jacobi Method
x=zeros(n,1);
k=1;
relres = 1;
info=0;
while k<=MaxIter && relres>TOL
for i=1:n
x(i)=(b(i)-A(i,[1:i-1,i+1:n])*x([1:i-1,i+1:n]))/A(i,i);
end
k=k+1;
info=info+1;
relres = norm(A*x-b)/norm(b);
end
disp(k)
end
This is my code of Jacobi method for calculating a certain system. My issue is that I think the program runs very slow and how would we solve this issue. Note that I want to calculate three things which are "x","info" and "relres". "x" is the solution, "relres" is the reltive residue and "info" records total number of iterations when the algorithm doesn't fail. Could someone help with this? Thanks a lot.

답변 (1개)

John D'Errico
John D'Errico 2021년 3월 16일
편집: John D'Errico 2021년 3월 16일
If you think your code runs slowly, an important thing you want to do is look at the profiler tools in MATLAB.
help profile
Does it find a bottleneck in your code? In fact, I don't see anything that would be notably poor in your code. Could you have written it "better"? Arguably so, but your code does not appear poor in my eyes.
Perhaps as importantly is to understand that you DON'T want to use this method in general.
In the global spectrum of methods, it is rarely a good choice of methods. Yes, it is a good method to teach students, because they need to learn to program to solve other problems. In some cases, I've seen similar methods employed even for nonlinear problems that were known to be well-behaved.
But to ask why it runs slowly, perhaps better is to understand WHY and WHEN the Jacobi method converges, when it will fail to converge, and when it will converge rapidly. On what class of problems will it be rapidly convergent? For this, you should do some reading. Or perhaps it is something your instructor would like to explain to you. (Since yours is not a question about MATLAB at all.) After all, it is likely this is one reason you were asked to code this method.

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by