MATLAB: An example of using crammers rule or geuss elimination

#geuss #crammers

Just looking for a good example

Best Answer

  • Crammers
    A = [ ...];
    b = [...]';
    [nr,nc] = size(A);
    x = cram_rule(A,b);
    fprintf('****************\n')
    for i = 1:nr
    fprintf(' x(%d) = %5.3f \n',i,x(i))
    end
    fprintf('****************\n')
    function x = cram_rule(A,b)
    [nr,nc] = size(A);
    DA = det(A);
    for i = 1:nr
    C = A;
    C(:,i) = b;
    x(i) = det(C)/DA;
    end
    Geuss
    C = ...;
    [nr nc] = size(C);
    xn = [1:nr]';
    [xn X] = gauss_elim(nr,nc,xn,C);
    fprintf('****************\n')
    for i = 1:nr
    fprintf(' x(%d) = %5.3f\n',xn(i),X(i))
    end
    fprintf('****************\n')
    function [xn X] = gauss_elim(nr,nc,xn,C)
    % Forward Elimination
    for j = 1:nr-1
    for i = j+1:nr %row 1 pivot row
    C(i,:) = C(i,:) - (C(i,j)/C(j,j))*C(j,:);
    end
    end
    % Back Substitution
    for i = nr:-1:1
    sm = 0;
    for j = nr:-1:i+1
    sm = sm +X(j)*C(i,j);
    end
    X(i) = [C(i,nc) - sm]/C(i,i);
    end
    end