%GAUSS ROW REDUCTION
%(Selcuk Bayin, METU-NCC, bayin@metu.edu.tr)
%GAUSS ROW REDUCTION: eg.1
clc
A=[1 2 3 1;3 2 1 2;1 1 -1 -2]
%%
A(2,:)=A(2,:)-3*A(1,:)
%%
A(3,:)=A(3,:)-A(1,:)
%%
A(3,:)=A(3,:)-(1/4)*A(2,:)
%%
rref(A)
%%
%det(A)
%%
%GAUSS ROW REDUCTION: eg.2
clc
A=[1 2 3 4;3 2 1 2;1 1 1 3]
%For future use store A again as AA
AA=A;
%%
A(2,:)=A(2,:)-3*A(1,:)
%%
A(3,:)=A(3,:)-A(1,:)
%%
A(3,:)=A(3,:)-(1/4)*A(2,:)
%%
rref(A)
%%
AA
%%
%Det. of Coefficients. But first the matrix of coefficients
AAA=[1 2 3;3 2 1;1 1 1]
%%
det(AAA)
%%
%ROW REDUCTION WITH SINGLE 'FOR' LOOPS
%%
clc
A=[1 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;
%%
for i=1:4
A(i+1,:)=A(i+1,:)-(A(i+1,1)/A(1,1))*A(1,:);
end
A
%%
for j=2:4
A(j+1,:)=A(j+1,:)-(A(j+1,2)/A(2,2))*A(2,:);
end
A
%%
for k=3:4
A(k+1,:)=A(k+1,:)-(A(k+1,3)/A(3,3))*A(3,:);
end
A
%%
for l=4
A(l+1,:)=A(l+1,:)-(A(l+1,4)/A(4,4))*A(4,:);
end
A
%%
%Rewrite the original matrix
clc
AA
%%
rref(AA)
%DOUBLE LOOP VERSION OF ROW REDUCTION
%B is equal to A
%%
clc
B=[1 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]
%%
for j=1:4
    for i=j:4
B(i+1,:)=B(i+1,:)-(B(i+1,j)/B(j,j))*B(j,:);
    end
end
B
%%
%ROW REDUCTION WITH NO PIVOTING
clc
B=[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]
%%
for j=1:4
    for i=j:4
B(i+1,:)=B(i+1,:)-(B(i+1,j)/B(j,j))*B(j,:);
    end
end
B
%%
%THE ABOVE EXAMPLE WITH PARTIAL PIVOTING:
clc
B=[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]
%%
if B(1,1)<0.01
B([1,2],:)=B([2,1],:)
else
B
end
%%
for j=1:4
    for i=j:4
B(i+1,:)=B(i+1,:)-(B(i+1,j)/B(j,j))*B(j,:);
    end
end
B
%%
%ANOTHER EXAMPLE WITH PARTIAL PIVOTING:
clc
F=[0 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]
%%
if F(1,1)==0
F([1,2],:)=F([2,1],:)
else
F
end
%%
for j=1:4
    for i=j:4
F(i+1,:)=F(i+1,:)-(F(i+1,j)/F(j,j))*F(j,:);
    end
end
F
%%
%FLIPPING ROWS
%%
clc
G=[0 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]
%%
 if G(2,1)>G(1,1);
 G([1,2],:)=G([2,1],:);
 end
 G
%%
%EXAMPLE FROM KREYSZIG
clc
A=[0 8 2 -7;3 5 2 8;6 2 8 26]
%%
for j=1:2
    for i=j:2
        [val,idx]=max(abs(A(:,j)));
A([j,idx],:)=A([idx,j],:);
A(i+1,:)=A(i+1,:)-(A(i+1,j)/A(j,j))*A(j,:);
    end
end
%%
A
%%
rref(A)
%%
 
