- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
> 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
> 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
> 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
> 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
> 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
> 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
> 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
> 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
Advertisements