How to solve the simultaneous linear equations in R?


The data in simultaneous equations can be read as matrix and then we can solve those matrices to find the value of the variables. For example, if we have three equations as −

x + y + z = 6
3x + 2y + 4z = 9
2x + 2y – 6z = 3

then we will convert these equations into matrices and solve them using solve function in R.

Example1

 Live Demo

> A<-matrix(c(1,1,2,3,2,4,2,3,-6),nrow=3,byrow=TRUE)
> A

Output

   [,1] [,2] [,3]
[1,] 1    1    2
[2,] 3    2    4
[3,] 2    3    -6

 Live Demo

> b<-matrix(c(6,9,3))
> b

Output

[,1]
[1,] 6
[2,] 9
[3,] 3
> solve(A,b)

Output

[,1]
[1,] -3.0
[2,] 6.0
[3,] 1.5

Hence, the answer is x = -3, y = 6, and z = 1.5.

4x - 3y + x = -10
2x + y + 3z = 0
-1x + 2y - 5z = 17

Example2

 Live Demo

> A<-matrix(c(4,-3,1,2,1,3,-1,2,-5),nrow=3,byrow=TRUE)
> A

Output

   [,1] [,2] [,3]
[1,] 4    -3    1
[2,] 2    1     3
[3,] -1    2    -5

Live Demo

> b<-matrix(c(-10,0,17))
> b

Output

[,1]
[1,] -10
[2,] 0
[3,] 17


> solve(A,b)

Output

[,1]
[1,] 1
[2,] 4
[3,] -2

Example3

4x – 2y + 3z = 1
x + 3y – 4z = -7
3x + y + 2z = 5

Live Demo

> A<-matrix(c(4,-2,3,1,3,-4,3,1,2),nrow=3,byrow=TRUE)
> A

Output

   [,1] [,2] [,3]
[1,] 4    -2    3
[2,] 1    3    -4
[3,] 3    1    2

 Live Demo

> b<-matrix(c(1,-7,5))
> b

Output

[,1]
[1,] 1
[2,] -7
[3,] 5


> solve(A,b)

Output

[,1]
[1,] -1
[2,] 2
[3,] 3

Example4

x + 2y – 3z + 4t = 12
2x + 2y – 2z + 3t = 10
y + z = -1
x - y + z – 2t = -4

Live Demo

> A<-matrix(c(1,2,-3,4,2,2,-2,3,0,1,1,0,1,-1,1,-2),nrow=4,byrow=TRUE)
> A

Output

   [,1] [,2] [,3] [,4]
[1,] 1    2    -3    4
[2,] 2    2    -2    3
[3,] 0    1    1    0
[4,] 1    -1    1    -2

 Live Demo

> b<-matrix(c(12,10,-1,-4))
> b

Output

[,1]
[1,] 12
[2,] 10
[3,] -1
[4,] -4


> solve(A,b)

Output

[,1]
[1,] 1
[2,] 0
[3,] -1
[4,] 2

Updated on: 04-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements