首页 > 解决方案 > Julia:我们如何计算伴随或经典伴随(线性代数)?

问题描述

我想计算古典伴随Julia 1.0

为此,我复制了在维基百科中作为示例给出的矩阵

julia> B = [-3 2 -5; -1 0 -2; 3 -4 1]
3×3 Array{Int64,2}:
 -3   2  -5
 -1   0  -2
  3  -4   1

在我看来,这似乎是计算的转置B而不是它的伴随。相反,我们应该得到这个(来自维基百科):

并尝试使用这里adjoint()的 Julia 文档中提到的函数来获得它的伴随,尽管文档没有具体说明这个函数的作用

julia> adjoint(B)
3×3 Adjoint{Int64,Array{Int64,2}}:
 -3  -1   3
  2   0  -4
 -5  -2   1

相反,我想得到这个:

在此处输入图像描述

在 Matlab 中,我确实得到:

>> adjoint(B)

ans =

   -8.0000   18.0000   -4.0000
   -5.0000   12.0000   -1.0000
    4.0000   -6.0000    2.0000

标签: julialinear-algebra

解决方案


Julia 的伴随定义为输入矩阵的复共轭的转置。但是,您似乎想要辅助矩阵:

共轭有时被称为“伴随”,但今天矩阵的“伴随”通常指的是它对应的伴随算子,也就是它的共轭转置。

您可以通过求逆然后乘以行列式来计算辅助矩阵:

julia> det(B) * inv(B)
3×3 Array{Float64,2}:
 -8.0  18.0  -4.0
 -5.0  12.0  -1.0
  4.0  -6.0   2.0

感谢 Julia Slack 上的 @Antoine Levitt 和 @Syx Pek 提供了用行列式求逆和乘法的建议。


原答案:

辅助矩阵似乎是辅因子矩阵的转置。下面是寻找辅因子的简单实现:

# import Pkg; Pkg.add("InvertedIndices")
using InvertedIndices # for cleaner code, you can remove this if you really want to.
function cofactor(A::AbstractMatrix, T = Float64)
           ax = axes(A)
           out = similar(A, T, ax)
           for col in ax[1]
               for row in ax[2]
                   out[col, row] = (-1)^(col + row) * det(A[Not(col), Not(row)])
               end
           end
           return out
       end

然后,要找到对等词,您只需要转置 ( transpose(cofactor(B)))。

答案是:

julia> cofactor(B, Float64) |> transpose
3×3 Transpose{Float64,Array{Float64,2}}:
 -8.0  18.0  -4.0
 -5.0  12.0  -1.0
  4.0  -6.0   2.0

这相当于Matlab给出的。

编辑:Julia slack 上的@Antoine Levitt 指出,这本质上是一个重新缩放的逆矩阵,所以如果你计算出缩放因子,你就可以这样做inv(B) * scaling_factor(在这个矩阵的情况下,它是 6)。


推荐阅读