38

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.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
mlzboy
  • 14,343
  • 23
  • 76
  • 97

4 Answers4

33

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
MYaseen208
  • 22,666
  • 37
  • 165
  • 309
13

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))
mpalanco
  • 12,960
  • 2
  • 59
  • 67
5

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.

banbh
  • 1,331
  • 1
  • 13
  • 31
  • Is there any benefit to this method? Precision? Computation speed? – Gimelist Apr 27 '20 at 14:11
  • I have not done any benchmarking, but if I were to guess directly using matrices is probably the fastest. However, I use the `lm` approach if it helps explain the purpose of my code. This is clearly a vague criterion; in my case if `x`, `y`, and `z` are variables or factors in my analysis then I may use `lm`. – banbh Apr 28 '20 at 14:52
-3
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!

Sampada
  • 2,931
  • 7
  • 27
  • 39
  • 2
    how is this substantively different from the previously posted answers? (note that `solve(A,b)` is equivalent to but more efficient than `solve(A) %*% b`) – Ben Bolker Mar 15 '17 at 11:26