R 中矩阵的逆
我想知道你推荐的计算矩阵逆的方法是什么?
我找到的方法似乎并不令人满意。例如,
> c=rbind(c(1, -1/4), c(-1/4, 1))
> c
[,1] [,2]
[1,] 1.00 -0.25
[2,] -0.25 1.00
> inv(c)
Error: could not find function "inv"
> solve(c)
[,1] [,2]
[1,] 1.0666667 0.2666667
[2,] 0.2666667 1.0666667
> solve(c)*c
[,1] [,2]
[1,] 1.06666667 -0.06666667
[2,] -0.06666667 1.06666667
> qr.solve(c)*c
[,1] [,2]
[1,] 1.06666667 -0.06666667
[2,] -0.06666667 1.06666667
谢谢!
I was wondering what is your recommended way to compute the inverse of a matrix?
The ways I found seem not satisfactory. For example,
> c=rbind(c(1, -1/4), c(-1/4, 1))
> c
[,1] [,2]
[1,] 1.00 -0.25
[2,] -0.25 1.00
> inv(c)
Error: could not find function "inv"
> solve(c)
[,1] [,2]
[1,] 1.0666667 0.2666667
[2,] 0.2666667 1.0666667
> solve(c)*c
[,1] [,2]
[1,] 1.06666667 -0.06666667
[2,] -0.06666667 1.06666667
> qr.solve(c)*c
[,1] [,2]
[1,] 1.06666667 -0.06666667
[2,] -0.06666667 1.06666667
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
solve(c)
确实给出了正确的逆。您的代码的问题是您使用了错误的矩阵乘法运算符。您应该使用solve(c) %*% c
来调用 R 中的矩阵乘法。当您调用
solve(c) * c
时,R 会执行逐个元素的乘法。solve(c)
does give the correct inverse. The issue with your code is that you are using the wrong operator for matrix multiplication. You should usesolve(c) %*% c
to invoke matrix multiplication in R.R performs element by element multiplication when you invoke
solve(c) * c
.您可以使用MASS包中的函数ginv()(Moore-Penrose广义逆)
You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package
请注意,如果您关心速度并且不需要担心奇异性,则
solve()
应优先于ginv()
,因为它要快得多,您可以检查:Note that if you care about speed and do not need to worry about singularities,
solve()
should be preferred toginv()
because it is much faster, as you can check:如果矩阵大于 1820x1820,请使用
solve(matrix)
。使用matlib
中的inv()
或MASS
中的ginv()
需要更长时间或根本无法解决,因为内存限制。Use
solve(matrix)
if the matrix is larger than 1820x1820. Usinginv()
frommatlib
orginv()
fromMASS
takes longer or will not solve at all because of RAM limits.