title: Jacobi iteration doesn't end
body: <p>I'm trying to implement the Jacobi iteration in MATLAB but am unable to get it to converge. I have looked online and elsewhere for working code for comparison but am unable to find any that is something similar to my code and still works. Here is what I have:</p>
  
  <pre><code>function x = Jacobi(A,b,tol,maxiter)
  
  n = size(A,1);
  xp = zeros(n,1); 
  x = zeros(n,1); 
  k=0; % number of steps
  
  while(k&lt;=maxiter)
      k=k+1;
  
      for i=1:n
         xp(i) = 1/A(i,i)*(b(i) - A(i,1:i-1)*x(1:i-1) - A(i,i+1:n)*x(i+1:n));
      end
  
      err = norm(A*xp-b);
  
      if(err&lt;tol)
          x=xp;
          break;
      end
  
      x=xp;
  
  end
  </code></pre>
  
  <p>This just blows up no matter what A and b I use. It's probably a small error I'm overlooking but I would be very grateful if anyone could explain what's wrong because this should be correct but is not so in practice.</p>