Solving System of Equations in R With Example
In this article, we will discuss solving a system of equations in the R Programming Language. solve() function in R Language is used to solve the equation. Here equation is like a*x = b, where b is a vector or matrix and x is a variable whose value is going to be calculated.
Related post: R PROGRAMMING MADE EASY
Syntax: solve(a, b)
Parameters:
- a: coefficients of the equation
- b: vector or matrix of the equation
Example 1: Solving system equation of three equations
Given Equations: x + 2y + 3z = 20 2x + 2y + 3z = 100 3x + 2y + 8z = 200Matrix A and B for solution using coefficient of equations: A-> 1 2 3 2 2 3 3 2 8 B-> 20 100 200
To solve this using two matrices in R we use the following code:
# create matrix A and B using given equations A <- rbind(c(1, 2, 3), c(2, 2, 3), c(3, 2, 8)) B <- c(20, 100, 200) # Solve them using solve function in R solve(A, B)
Output:
Example 2: Solving system equation of three equations
To get solutions in form of fractions, we use the library MASS in R Language and wrap solve function in fractions.
Given Equations: 19x + 32y + 31z = 1110 22x + 28y + 13z = 1406 31x + 12y + 81z = 3040Matrix A and B for solution using coefficient of equations: A-> 19 32 31 22 28 13 31 12 81 B-> 1110 1406 3040
To solve this using two matrices in R we use the following code:
# Load package MASS library(MASS) # create matrix A and B using given equations A <- rbind(c(19, 32, 31), c(22, 28, 31), c(31, 12, 81)) B <- c(1110, 1406, 3040) # Solve them using solve # function wrapped in fractions fractions(solve(A, B))
Output:
[1] 159950/2243 -92039/4486 29784/2243 which means x=159950/2243 , y=-92039/4486 and z=29784/2243 is the solution for the above given linear equation.
Example 3: Solving Inverse matrix
# create matrix A and B using given equations A <- matrix(c(4, 7, 3, 6), ncol = 2) print(A) print("Inverse matrix") # Solve them using solve function in R print(solve(A))
Output:
[,1] [,2] [1,] 4 3 [2,] 7 6 [1] "Inverse matrix" [,1] [,2] [1,] 2.000000 -1.000000 [2,] -2.333333 1.333333
Originally published at https://pyoflife.com on August 1, 2022.