%AUTOMATIC PARTIAL PIVOTING AND ROW REDUCTION:
%(Selcuk Bayin, METU-NCC, bayin@metu.edu.tr)
clc
A=[0.000001 2 3 4 -1 2;3 2 1 3 2 3;1 1 4 1 3 1;2 4 1 -1 1 4;1 3 4 1 -2 3]
AA=A;
%%
n=5;
%Row Echelon Form
for k=1:n-1
    [val,idx]=max(abs(A([k:end],k)));
    if k==1
A([k,idx],:)=A([idx,k],:);
    else
        A([k,idx+k-1],:)=A([idx+k-1,k],:);
    end
    for i=k:n-1
A(i+1,:)=A(i+1,:)-(A(i+1,k)/A(k,k))*A(k,:);
    end
end 
%Reduced Row Echelon Form
A
%%
n=5;
for k=1:n-1
    k=n-k+1;
    [val,idx]=max(abs(A([k:end],k)));
    if k==1
A([k,idx],:)=A([idx,k],:);
    else
        A([k,idx+k-1],:)=A([idx+k-1,k],:);
    end
    for i=n-k+1:n-1
A(n-i,:)=A(n-i,:)-(A(n-i,k)/A(k,k))*A(k,:);
    end
end 
A
%%
A(1,:)=A(1,:)/A(1,1);
A(2,:)=A(2,:)/A(2,2);
A(3,:)=A(3,:)/A(3,3);
A(4,:)=A(4,:)/A(4,4);
A(5,:)=A(5,:)/A(5,5);
A
%Comparison with RREF Command
%%
MathLabRREF=rref(AA)


