Gaussian Elimination of Matrices in Matlab

January 31, 2019

Gaussian elimination uses Elementary Matrix Operations to yield a pair of lower & higher triangle matrices for which:

A = LU

Gaussian Elimination without a pivot:

function [A] = gauss(A)
    n = size(A);

    % Initialize L & U Matrices
    l = zeros(n);
    u = zeros(n);

    for k = 1:n
        l(k, k) = 0;

        for j = k:n
            sumValue = 0;
            for s=1:k-1
                sumValue = sumValue + l(k, s) * u(s, j);
            end
            
            u(k, j) = A(k, j) - sumValue;
        end

        for i = k+1:n
            sumValue = 0;
            for s=1:k-1
                sumValue = sumValue + l(i, s) * u(s, k);
            end
            
            l(i, k) = (A(i, k) - sumValue) / u(k, k);
        end
    end
    
    A = l + u;
end

Gaussian Elimination with pivoting:

function [l, A] = gauss_p(A)
    n = size(A, 1);

    % Initialize Matrices
    l = zeros(1, n);
    s = zeros(1, n);
    
    rmax = 0;

    for i = 1:n
        l(1, i) = i;
        smax = 0;

        for j = 1:n
            smax = max(smax, abs(A(i, j)));
        end
        
        s(1, i) = smax;
    end
    
    for k=1:n-1
        rmax = 0;
        
        for i=k:n
            r = abs(A(l(1, i), k) / s(1, l(1, i)));
            
            if (r > rmax)
                rmax = r;
                j = i;
            end
        end
        
        temp = l(1, j);
        l(1, j) = l(1, k);
        l(1, k) = temp;
        
        for i=k+1:n
            xmult = A(l(1, i), k) / A(l(1, k), k);
            A(l(1, i), k) = xmult;
            
            for j = k+1:n
                A(l(1, i), j) = A(l(1, i), j) - (xmult * A(l(1, k), j));
            end
        end
    end
    
    clear s;
end