Solving simultaneous equations with R

余生长醉 提交于 2019-11-27 00:52:46

问题


Suppose I have the following equations:

 x + 2y + 3z = 20  
2x + 5y + 9z = 100  
5x + 7y + 8z = 200

How do I solve these equations for x, y and z? I would like to solve these equations, if possible, using R or any other computer tools.


回答1:


This should work

A <- matrix(data=c(1, 2, 3, 2, 5, 9, 5, 7, 8), nrow=3, ncol=3, byrow=TRUE)    
b <- matrix(data=c(20, 100, 200), nrow=3, ncol=1, byrow=FALSE)
round(solve(A, b), 3)

     [,1]
[1,]  320
[2,] -360
[3,]  140



回答2:


For clarity, I modified the way the matrices were constructed in the previous answer.

a <- rbind(c(1, 2, 3), 
           c(2, 5, 9), 
           c(5, 7, 8))
b <- c(20, 100, 200)
solve(a, b)

In case we need to display fractions:

library(MASS)
fractions(solve(a, b))



回答3:


Another approach is to model the equations using lm as follows:

lm(b ~ . + 0, 
   data = data.frame(x = c(1, 2, 5), 
                     y = c(2, 5, 7), 
                     z = c(3, 9, 8), 
                     b = c(20, 100, 200)))

which produces

Coefficients:
   x     y     z  
 320  -360   140

If you use the tibble package you can even make it read just like the original equations:

lm(b ~ . + 0, 
   tibble::tribble(
     ~x, ~y, ~z,  ~b,
      1,  2,  3,  20,
      2,  5,  9, 100,
      5,  7,  8, 200))

which produces the same output.




回答4:


A <- matrix(data=c(1, 2, 3, 2, 5, 9, 5, 7, 8),nrow=3,ncol=3,byrow=TRUE)    
b <- matrix(data=c(20, 100, 200),nrow=3,ncol=1,byrow=FALSE)
solve(A)%*% b

Note that this is a square matrix!



来源:https://stackoverflow.com/questions/8145694/solving-simultaneous-equations-with-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!