function [x,k]=jacobi_func1(A,b,xinit,itermax,tol)
% jacobi1 script converted to a function

n=length(b);

x=xinit;

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);
    % check convergence
    if norm( x - xprev ) <= tol
        break
    end
end

end