function [P,dP,Z] = jacobi(A,B,P,delta,max1)
% [X,dX] = jacobi(A,B,P,delta,max1)
% [X,dX,Z] = jacobi(A,B,P,delta,max1)
% A is an nxn diagonally dominant matrix, input.
% B is a nx1 vector, input.
% P is an nX1 starting vector, input.
% The tolerance is delta, input.
% The maximum number of iterations is max1, input.
% X is an nx1 vector, output.
% dX is an nx1 vector, output.
% Z is a list of iterations, output.
Z = P';
n = length(B);
Pnew = P;
for k=1:max1,
for r = 1:n,
Sum1 = B(r) - A(r,[1:r-1,r+1:n])*P([1:r-1,r+1:n]);
Pnew(r) = Sum1/A(r,r);
end
dP = abs(Pnew-P);
err = norm(dP);
relerr = err/(norm(Pnew)+eps);
P = Pnew;
Z = [Z;P'];
if (err<delta)|(relerr<delta), break, end
end