Search code examples
wolfram-mathematicadeterminants

Algorithm to find the determinant of a matrix


I have to write an algorithm to find the determinant of a matrix, which is done with the recursive function:

enter image description here

where A_ij is the matrix, which appears when you remove the ith row and the jth column for A. When A has dimension n x n, then the dimension for A_ij is (n-1) x (n-1). I'm not allowed to use Minor[] or Det[].

How do I write this algorithm?


This is the code I have so far:

det1[Mi_ /; Dimensions[Mi][[1]] == Dimensions[Mi][[2]]] :=
  Module[{det1}, 
    det1 = Sum[ 
      If[det1 == 1, Break[], (-1)^(1 + j) *Mi[[1, j]]*det1[Drop[Mi, {1}, {j}]]], 
      {j, 1, Length[Mi]}]; 
    Return[det1 // MatrixForm, Module]
] 

Solution

  • Why doesn't your code work?

    1. MatrixForm is used for formatting (display), but a MatrixForm-wrapped matrix can't be used in calculations. You simply need to remove it.

    2. Think about your stopping condition for the recursion: the determinant of a 1*1 matrix is just the single element of the matrix. Rewrite the sum and If based on this. If the matrix is of size 1, return its element (it's impossible to Break[] out of a recursion).

    3. Don't use a local variable with the same name as your function: this masks the global function and makes it impossible to call recursively.

    4. Finally, this doesn't break the function, but an explicit Return is not necessary. The last value of a CompoundExpression is simply returned.


    To summarize, det[m_] := If[Length[m] == 1, m[[1,1]], (Laplace expansion here)]. An alternative is to use pattern matching to identify size-1 matrices:

    Clear[det]
    det[{{x_}}] := x
    det[m_] := (Laplace expansion)