%naive algorithm for forward/backward Gaussian elimination for matrix A
%can be used to solve Ax = b or to invert a matrix A

A = [6,-2,2,4,16;12,-8,6,10,26;3,-13,9,3,-19;-6,4,1,-18,-34]

[m,n] = size(A);       %A is m by n

%forward elimination

for k=1:m-1
    for i=k+1:m
        c = A(i,k)/A(k,k);   %c = multiple of row k to subtract from row i
        A(i,k) = 0;
        for j=k+1:n
            A(i,j) = A(i,j)-c*A(k,j);
        end
    end
end

%backward elimination

for k=m:-1:2          %loop goes from m to 2 (the -1 means it's backwards)
    for i=1:k-1
        c = A(i,k)/A(k,k);   %c = multiple of row k to subtract from row i
        A(i,k) = 0;
        for j=m+1:n
            A(i,j) = A(i,j)-c*A(k,j);
        end
    end
end

%scale rows 

for i=1:m
    c = A(i,i);
    A(i,i) = 1;
    for j=m+1:n
        A(i,j) = A(i,j)/c;
    end
end

disp('the reduced matrix is...')
A
