% generalized version of Jacobi iteration script 
% using row*column vector multiplication to calculate terms to be subtracted
% (can be converted to a function)

A=[7 2 -3 1; -4 8 1 -2; 3 -2 9 2; 1 -1 1 4];
b=[-1;16;-3;5];

x=[1;1;1;1]; % initial guess

itermax=50;
tol=1e-8;

n=length(b);

for k=1:itermax
    % assign most recent x to xprev
    xprev=x;
    % calculate new x
    x(1)=(b(1) - A(1,2:n)*xprev(2:n))/A(1,1);
    for i=2:n-1
		x(i)=(b(i) - A(i,1:i-1)*xprev(1:i-1) - A(i,i+1:n)*xprev(i+1:n))/A(i,i);
    end
    x(n)=(b(n) - A(n,1:n-1)*xprev(1:n-1))/A(n,n);    
    % print iteration number and the x just computed
    fprintf('%2d',k)
    for i=1:n-1
        fprintf('%12.8f  ',x(i))
    end
    fprintf('%12.8f\n',x(n))
    % check convergence
    if norm( x - xprev ) <= tol
        break
    end
end