function x = LU_rowPivot(A,b,n)
% LU factorization of an n by n matrix A
% using Gauss elimination with row pivoting.
% b is an n by 1 vector.
% The solution to Ax = b is returned in x.
% LU_rowPivot.m
% U is upper triangular and is stored in the upper triangular
% part of A; the remaining part has no special meaning
% and must be zeroed out to get U.
% The permutation matrix P is created but not returned here.
% K. Ming Leung, 02/22/04

M=eye(n); P=eye(n);
for k = 1:n-1
    [pivot, p] = max(abs(A(k:n,k)));
    p = k+p-1;
    if (p ~= k)
        A = swapRow(A,k,p);
        b = swapRow(b,k,p);
        P = swapRow(P,k,p);
    end
    
    if (A(k,k) ~= 0) 
        M(k+1:n,k) = A(k+1:n,k)/A(k,k);
        i = k+1:n;
        A(i,i) = A(i,i) - M(i,k)*A(k,i);
        b(i) = b(i) - M(i,k)*b(k);
    end
end

x = backSubstitution(A,b,n);


     