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

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]
]
Why doesn’t your code work?
MatrixFormis used for formatting (display), but a MatrixForm-wrapped matrix can’t be used in calculations. You simply need to remove it.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
Ifbased on this. If the matrix is of size 1, return its element (it’s impossible toBreak[]out of a recursion).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.
Finally, this doesn’t break the function, but an explicit
Returnis not necessary. The last value of aCompoundExpressionis 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: