简体   繁体   English

求解 R 中的联立方程

[英]Solving simultaneous equation in R

I want to solve the following simultaneous equations using R:我想使用 R 求解以下联立方程:

# -0.9x+0.01y+0.001z+0.001n=0
# 0.9x-0.82y+0.027z+0.027n=0
# 0x+0.81y+(0.243-1)z+0.243n=0
# 0x+0y+0.729z+(0.729-1)n=0
# x+y+z+n=1

I tried:我试过了:

A <- matrix(data=c(-0.9,0.01,0.001,0.001,0.9,-0.82,0.027,0.027,0,0.81,0.243-1,0.243,0,0,0.729,0.729-1,1,1,1,1), nrow=5, ncol=4, byrow=TRUE)    
b <- matrix(data=c(0, 0, 0, 0, 1), nrow=5, ncol=1, byrow=FALSE)
round(solve(A, b), 4)

and it caught error:它发现了错误:

Error in solve.default(A, b) : 'a' (5 x 4) must be square

What does the error mean?错误是什么意思? Is this function only applicable to square matrix?这个 function 是否只适用于方阵?


Edit:编辑:

I removed the last equation and tried:我删除了最后一个等式并尝试:


A <- matrix(data=c(-0.9,0.01,0.001,0.001,0.9,-0.82,0.027,0.027,0,0.81,0.243-1,0.243,0,0,0.729,0.729-1), nrow=4, ncol=4, byrow=TRUE)    
b <- matrix(data=c(0, 0, 0, 0), nrow=4, ncol=1, byrow=FALSE)
A;b;
round(solve(A, b), 4)

which caught error:捕获错误:

Error in solve.default(A, b) : Lapack routine dgesv: system is exactly singular: U[4,4] = 0

Since you have 5 linear equations (rows of your matrix) and only 4 columns (variables), then your problem is overdetermined and in general it can't be solved.由于您有 5 个线性方程(矩阵的行)和只有 4 列(变量),因此您的问题是超定的,通常无法解决。 Consider a smaller example: x+y=1; x-2*y=2; 3*x-5=0考虑一个更小的例子: x+y=1; x-2*y=2; 3*x-5=0 x+y=1; x-2*y=2; 3*x-5=0 x+y=1; x-2*y=2; 3*x-5=0 . x+y=1; x-2*y=2; 3*x-5=0 Once you use the first two equations:使用前两个等式后:

(1) x+y=1        → y=1-x
(2) x-2*(1-x)=2  → 3*x-2=2 → x=4/3  ## substitute (1) into second eq.
(3) → y=-1/3

you have a solution for x and y (x=4/3, y=-1/3), so the last equation is either redundant or makes your solution impossible (in this case, the latter: 3*x-5 = -1 != 5 ).你有一个 x 和 y 的解(x=4/3, y=-1/3),所以最后一个方程要么是多余的,要么使你的解不可能(在这种情况下,后者: 3*x-5 = -1 != 5 )。

On the other hand, if you have fewer rows than columns, then your system is underdetermined and you can't get a unique answer.另一方面,如果您的行数少于列数,那么您的系统是不确定的,并且您无法获得唯一的答案。

So the number of matrix rows must equal the number of columns → you can only do this with a square matrix.所以矩阵行数必须等于列数→你只能用方阵来做到这一点。 This is not a limitation of the R function, it's about the underlying math of linear equations...这不是 R function 的限制,它是关于线性方程的基础数学......

In your specific case the problem is that the sum of the first four rows of your matrix add up to zero, so these are redundant .在您的特定情况下,问题是矩阵的前四行之和加起来为零,因此这些是多余的。 As you found out, just dropping the last equation doesn't help.正如您所发现的,仅仅删除最后一个等式并没有帮助。 But if you drop one of the redundant rows you can get an answer.但是,如果您删除其中一个冗余行,您可以获得答案。

solve(A[-4,],b[-4])

Note you get the same answer whether you drop row 1, 2, 3, or 4.请注意,无论您删除第 1、2、3 还是 4 行,您都会得到相同的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM