You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言solve函数计算矩阵逆与手动计算结果不符的问题

矩阵逆计算结果不一致的问题分析

问题重现

我需要计算矩阵的逆,已排除普通逆函数及matrix-inverse标签下的多数结果,示例矩阵及相关操作如下:

创建矩阵

#### Create Matrix ####
mat <- matrix(
  c(4,2,7,6),
  nrow=2
)
mat

输出:

[,1] [,2]
[1,]    4    7
[2,]    2    6

手动计算尝试

我尝试通过行列式推导逆矩阵,写了如下代码:

1/((4*6)-(7*2))*mat # 1/det
(1/det(mat))*mat # same

得到输出:

[,1] [,2]
[1,]  0.6 -0.7
[2,] -0.2  0.4

solve函数结果

但使用solve(mat)得到的结果却不同:

[,1] [,2]
[1,]  0.4  0.7
[2,]  0.2  0.6

重启R后结果仍无变化,我的会话信息:

R version 4.2.1 (2022-06-23 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 22621)

Matrix products: default

locale:
[1] LC_COLLATE=Chinese (Simplified)_China.utf8 
[2] LC_CTYPE=Chinese (Simplified)_China.utf8   
[3] LC_MONETARY=Chinese (Simplified)_China.utf8
[4] LC_NUMERIC=C                                
[5] LC_TIME=Chinese (Simplified)_China.utf8    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] compiler_4.2.1  tools_4.2.1     rstudioapi_0.14

此外,运行solve(mat) %*% mat得到:

[,1]         [,2]
[1,]    1 8.881784e-16
[2,]    0 1.000000e+00

请问结果不同的原因是什么?是否需要使用替代函数?


问题原因与解答

核心错误:矩阵逆的计算公式理解错误

2x2矩阵的逆矩阵不是 (1/行列式) × 原矩阵,正确公式是:
[
A^{-1} = \frac{1}{\text{det}(A)} \times \text{伴随矩阵}
]
对于2x2矩阵 (\begin{pmatrix}a & b \ c & d\end{pmatrix}),伴随矩阵是原矩阵的代数余子式矩阵的转置,即 (\begin{pmatrix}d & -b \ -c & a\end{pmatrix})。

回到你的示例:

  • 原矩阵行列式 (\text{det}(mat) = 4×6 -7×2 = 10)
  • 伴随矩阵为 (\begin{pmatrix}6 & -7 \ -2 & 4\end{pmatrix})
  • 正确的逆矩阵应为 (\frac{1}{10} × \begin{pmatrix}6 & -7 \ -2 & 4\end{pmatrix} = \begin{pmatrix}0.6 & -0.7 \ -0.2 & 0.4\end{pmatrix})

结果混淆的说明

你记录的输出存在明显矛盾:

  • (1/det(mat))*mat 的实际计算结果应为 (\begin{pmatrix}0.4 & 0.7 \ 0.2 & 0.6\end{pmatrix}),这个矩阵乘以原矩阵不会得到单位矩阵;
  • 而你给出的solve(mat) %*% mat结果接近单位矩阵,说明solve(mat)的实际输出应该是正确的逆矩阵 (\begin{pmatrix}0.6 & -0.7 \ -0.2 & 0.4\end{pmatrix}),你大概率是在记录时把两种操作的输出写反了。

结论

  1. 结果不一致的根本原因是你错误地用原矩阵代替伴随矩阵进行逆矩阵计算;
  2. solve()是R中计算矩阵逆的标准可靠函数,无需使用替代函数;
  3. 修正手动计算代码即可得到和solve()一致的结果,正确代码应为:
(1/det(mat)) * matrix(c(6, -2, -7, 4), nrow = 2)

内容的提问来源于stack exchange,提问作者Shawn Hemelstrand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:25:16