问题
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 i
th row and the j
th 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]
]
回答1:
Why doesn't your code work?
MatrixForm
is 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
If
based 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
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)
回答2:
Does this solve your problem?
Clear[det];
det[{{x_}}] := x;
det[a_ /; MatrixQ[a] && SameQ @@ Dimensions[a]] :=
Sum[(-1)^(1 + i) a[[1, i]] det[Drop[a, {1}, {i}]], {i, 1, Length[a]}];
det::gofish = "Unable to handle this type of input: ``";
det[a___] := (Message[det::gofish, HoldForm[det][a]]; $Failed)
E.g., this:
In[]:=
m = {{a, b, c}, {c, d, e}, {f, g, h}};
Det[m] === Expand[det[m]]
gives:
Out[]=
True
来源:https://stackoverflow.com/questions/8507654/algorithm-to-find-the-determinant-of-a-matrix