用 R 求解非平方线性系统 [英] Solving non-square linear system with R
问题描述
如何用 R 求解非平方线性系统:A X = B
?
How to solve a non-square linear system with R : A X = B
?
(在系统无解或有无穷多个解的情况下)
(in the case the system has no solution or infinitely many solutions)
示例:
A=matrix(c(0,1,-2,3,5,-3,1,-2,5,-2,-1,1),3,4,T)
B=matrix(c(-17,28,11),3,1,T)
A
[,1] [,2] [,3] [,4]
[1,] 0 1 -2 3
[2,] 5 -3 1 -2
[3,] 5 -2 -1 1
B
[,1]
[1,] -17
[2,] 28
[3,] 11
推荐答案
如果矩阵 A 的行数多于列数,则应使用最小二乘法拟合.
If the matrix A has more rows than columns, then you should use least squares fit.
如果矩阵 A 的行数少于列数,则应执行奇异值分解.每个算法都尽其所能,通过使用假设为您提供解决方案.
If the matrix A has fewer rows than columns, then you should perform singular value decomposition. Each algorithm does the best it can to give you a solution by using assumptions.
这是一个显示如何使用 SVD 作为求解器的链接:
Here's a link that shows how to use SVD as a solver:
http://www.ecse.rpi.edu/~qji/简历/svd_review.pdf
让我们将其应用于您的问题,看看它是否有效:
Let's apply it to your problem and see if it works:
你的输入矩阵A
和已知的RHS向量B
:
Your input matrix A
and known RHS vector B
:
> A=matrix(c(0,1,-2,3,5,-3,1,-2,5,-2,-1,1),3,4,T)
> B=matrix(c(-17,28,11),3,1,T)
> A
[,1] [,2] [,3] [,4]
[1,] 0 1 -2 3
[2,] 5 -3 1 -2
[3,] 5 -2 -1 1
> B
[,1]
[1,] -17
[2,] 28
[3,] 11
让我们分解你的 A
矩阵:
Let's decompose your A
matrix:
> asvd = svd(A)
> asvd
$d
[1] 8.007081e+00 4.459446e+00 4.022656e-16
$u
[,1] [,2] [,3]
[1,] -0.1295469 -0.8061540 0.5773503
[2,] 0.7629233 0.2908861 0.5773503
[3,] 0.6333764 -0.5152679 -0.5773503
$v
[,1] [,2] [,3]
[1,] 0.87191556 -0.2515803 -0.1764323
[2,] -0.46022634 -0.1453716 -0.4694190
[3,] 0.04853711 0.5423235 0.6394484
[4,] -0.15999723 -0.7883272 0.5827720
> adiag = diag(1/asvd$d)
> adiag
[,1] [,2] [,3]
[1,] 0.1248895 0.0000000 0.00000e+00
[2,] 0.0000000 0.2242431 0.00000e+00
[3,] 0.0000000 0.0000000 2.48592e+15
这里是关键:d
中的第三个特征值非常小;相反,adiag
中的对角线元素非常大.在求解之前,将其设置为零:
Here's the key: the third eigenvalue in d
is very small; conversely, the diagonal element in adiag
is very large. Before solving, set it equal to zero:
> adiag[3,3] = 0
> adiag
[,1] [,2] [,3]
[1,] 0.1248895 0.0000000 0
[2,] 0.0000000 0.2242431 0
[3,] 0.0000000 0.0000000 0
现在让我们计算解决方案(请参阅上面我提供给您的链接中的幻灯片 16):
Now let's compute the solution (see slide 16 in the link I gave you above):
> solution = asvd$v %*% adiag %*% t(asvd$u) %*% B
> solution
[,1]
[1,] 2.411765
[2,] -2.282353
[3,] 2.152941
[4,] -3.470588
既然我们有了一个解决方案,让我们把它替换回去看看它是否给了我们相同的B
:
Now that we have a solution, let's substitute it back to see if it gives us the same B
:
> check = A %*% solution
> check
[,1]
[1,] -17
[2,] 28
[3,] 11
那是你开始的 B
方面,所以我认为我们很好.
That's the B
side you started with, so I think we're good.
这是来自 AMS 的另一个精彩的 SVD 讨论:
Here's another nice SVD discussion from AMS:
http://www.ams.org/samplings/feature-column/fcarc-svd
这篇关于用 R 求解非平方线性系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!