求矩阵行列式的算法 [英] Algorithm to find the determinant of a matrix

查看:47
本文介绍了求矩阵行列式的算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须写一个算法来找到矩阵的行列式,这是用递归函数完成的:

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

其中 A_ij 是矩阵,当您删除 A<的 i 行和 j 列时出现该矩阵/代码>.当A的维度为nxn,那么A_ij的维度为(n-1) x (n-1).我不允许使用 Minor[]Det[].

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?

这是我目前的代码:

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?

  1. MatrixForm 用于格式化(显示),但 MatrixForm 包装的矩阵不能用于计算.您只需将其删除即可.

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

考虑递归的停止条件:1*1 矩阵的行列式只是矩阵的单个元素.在此基础上重写 sum 和 If.如果矩阵的大小为 1,则返回其元素(不可能从递归中Break[]).

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).

不要使用与您的函数同名的局部变量:这会掩盖全局函数并使递归调用变得不可能.

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.

最后,这不会破坏函数,但是不需要显式的Return.CompoundExpression 的最后一个值被简单地返回.

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

<小时>

总而言之,det[m_] := If[Length[m] == 1, m[[1,1]],(这里是拉普拉斯展开式)].另一种方法是使用模式匹配来识别大小为 1 的矩阵:


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)

这篇关于求矩阵行列式的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆