%%--------------------------------------------------------------------------%%
%% gausspivot.m - Gaussian elimination with Partial Pivoting                %%
%%--------------------------------------------------------------------------%%
function X=gausspivot(A,b,n)

if (abs(det(A))<eps)
  disp(sprintf('A is singular with det=%f\n',det(A)))
end

C=[A, b];
%
% Gaussian Elimination with Partial Pivoting 
%
for i=1:n-1
  [pivot, k]=max(abs(C(i:n,i)));
  if (k>1)
    temp=C(i,:);
    C(i,:)=C(i+k-1,:);
    C(i+k-1,:)=temp;
  end
  m(i+1:n,i)= -C(i+1:n,i)/C(i,i);
  C(i+1:n,:)=C(i+1:n,:)+m(i+1:n,i)*C(i,:);
end
%
% Back substitution
%
X=zeros(n,1); %% Let X be a column vector of size n
X(n)=C(n,n+1)/C(n,n);
for i=n-1:-1:1
  X(i)=(C(i,n+1)-C(i,i+1:n)*X(i+1:n))/C(i,i);
end

