Back to home

Calculating Matrix Determinant Higher Than 2x2





The mathematics background for calculating matrix
determinant higher than 2x2 can be found here.

Since the calculation of matrix determinant of higher
dimension, say 4x4, requires the calculation of matrix
determinant of its smaller 3x3. This indirectly tells
us that we need to make a recursive function,

Updated: I also include a faster algorithm using
Gauss-Jordan elimination.

This is my solution:
------------------------------------------------------
type
  arr = array[1..4, 1..4] of real;

function determinant(a: arr; dim: integer): real;
var
  new_a : arr;
  j, c1, c2 : word;
  sum, factor : real;
begin
  if dim < 2 then
  begin
    writeln('Cannot determine determinant!');
    determinant := 0;
  end
  else if dim = 2 then
  begin
    determinant := a[1,1]*a[2,2] - a[2,1]*a[1,2];
  end else
  begin
    sum := 0;

    for j:=1 to dim do
    begin

      { Skip zero factors to speed up }
      if (a[1,j] <> 0) then
      begin

        { Creating new matrix }
        for c1:=2 to dim do
          for c2:=1 to dim do
          begin
            if c2 > j then new_a[c1-1,c2-1]:=a[c1,c2] else
               if c2 < j then new_a[c1-1,c2]:= a[c1,c2];
          end;

        { Recursive call to get the determinant of smaller }
        { matrix. Pay attention to this.                   }

        factor := a[1,j]*determinant(new_a, dim-1);

        { The alternating law applies here }
        if (j mod 2 = 0) then sum := sum - factor
           else sum := sum + factor;
      end;
    end;
    determinant := sum;
  end;
end;
------------------------------------------------------

Back to home


Roby Joehanes, © 2001

1