I've implemented the Jacobi method in matlab but when i try it , the function give me wrongs results.. I don't know what I'm wrong. I post here my code and results.
function [x,niter,resrel] = jacobiSolver(a, b, varargin)narginchk(2, 5); % check if the function receives the right number of input parameters
nargoutchk(0,3); % check if the function receives the right number of output parameters
checkAB(a,b) % priority control
% OPTIONAL PARAMETER CONTROL
switch nargin case 4; [TOL, NMAX] = CheckNMAX(varargin{1}, varargin{2}); case 3; [TOL, NMAX] = CheckTOL(varargin{1}, 500); case 2; TOL = 10^-6; NMAX = 500; otherwiseend% codifichiamo l'algoritmo => vedere se dobbiamo sostituire con spdiags
c = b./diag(a);B = (-1./diag(a)')' .*(a-diag(diag(a))); x0=zeros(length(b),1);x=c;nit = 0;%TOLX = max(TOL*norm(x,1),realmin);
TOLX = TOL;while norm(x-x0,1)>=TOLX && nit<NMAX x0 = x ; x = B*x0 + c; TOLX = max(realmin, TOL*norm(x0,1)); nit = nit+1end% IF THE NMAX VALUE IS REACHED THEN THE USER WILL BE NOTIFIED WITH A WARNING
if(nit==NMAX) warning("Limit reached, probably not convergence... calculation stopped and resrel = "+0);endif nargout > 1 niter = nit; if nargout == 3 resrel = 0; end endend
results obteined with simple matrix a and b:
Warning: Limit reached, probably not convergence... calculation stopped and resrel = 0 > In jacobiSolver (line 32) ans = 1.0e+295 * 0.3636 1.2137 0.7255 0.9811 1.0341
correct results:
ans = 20.2162 -43.2162 -56.8378 102.1081 -21.7838
also are there better ways to implement this algorithm?
thanks a lot for helping!
Best Answer