Algorithm to find the determinant of a matrix

可紊 提交于 2020-01-07 02:17:10

问题


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]
] 

回答1:


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)



回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!