R 中矩阵的逆

发布于 2024-10-03 23:45:50 字数 574 浏览 5 评论 0原文

我想知道你推荐的计算矩阵逆的方法是什么?

我找到的方法似乎并不令人满意。例如,

> 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

ゃ人海孤独症 2024-10-10 23:45:50

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 use solve(c) %*% c to invoke matrix multiplication in R.

R performs element by element multiplication when you invoke solve(c) * c.

乖乖公主 2024-10-10 23:45:50

您可以使用MASS包中的函数ginv()(Moore-Penrose广义逆)

You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package

苹果你个爱泡泡 2024-10-10 23:45:50

请注意,如果您关心速度并且不需要担心奇异性,则 solve() 应优先于 ginv(),因为它要快得多,您可以检查:

require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)

t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0 

t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1 

Note that if you care about speed and do not need to worry about singularities, solve() should be preferred to ginv() because it is much faster, as you can check:

require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)

t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0 

t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1 
╄→承喏 2024-10-10 23:45:50

如果矩阵大于 1820x1820,请使用 solve(matrix)。使用 matlib 中的 inv()MASS 中的 ginv() 需要更长时间或根本无法解决,因为内存限制。

Use solve(matrix) if the matrix is larger than 1820x1820. Using inv() from matlib or ginv() from MASS takes longer or will not solve at all because of RAM limits.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文