Today, we will learn how to use the R solve() function to solve equations and inverse matrices. Please read to the end of the article to learn how to use this function.
What is the solve() function in R?
The solve() function in R is used to solve equations. For example, in this case, an equation is a*x = b, where b is a matrix or vector, and x is a variable whose value will be determined.
- a: The equation’s coefficients
- b: The equation’s matrix or vector
How to use this function?
The basic equation
In this example, we will use the solve() function to solve a single equation.
If we want to solve the following equation: 6x = 30, we can easily see a = 6 and b = 30, so we can use the R code below to solve:
# Solve the equation 6x = 30 x <- solve(6,30) cat("x= ");x
x=  5
Solve three equations in a system
If you want to solve complex systems of equations, you can use the solve() function. Assume that our equation system looks like this:
2x + 1y + 3z = 20
5x + 2y + 5z = 40
5x + 1y + 2z = 10
Here, we will have two matrix A and B as follows:
2 1 3
5 2 5
5 1 2
Following the code below, we will solve this matrix:
# Create matrix A and B A <- rbind( c(2, 1, 3), c(5, 2, 5), c(5, 1, 2) ) B <- c(20, 40, 10) # Using solve function to solve them res <- solve(A, B) res
 -5 45 -5
To solve inverse matrix
If the right-hand side matrix is not explicitly supplied, the solution function sets it to the identity matrix. In other words, if no right-hand side matrix is supplied, the solve function computes the inverse of a matrix.
Let’s take this into practice: First, we must generate another example matrix in R:
# Create a complex matrix set.seed(10000) # Create a matrix mat <- matrix(rnorm(16),nrow = 4) # View matrix mat
[,1] [,2] [,3] [,4] [1,] 0.5009103 0.3108103 -0.5412128 0.60377924 [2,] 0.1744218 0.3432122 1.8712320 0.02941477 [3,] -0.3329998 -0.9400177 0.1401120 -0.46298819 [4,] -0.6930059 0.7979436 -0.7248476 -0.07789984
Now, we can use the solve() function to solve this matrix (i.e. compute the inverse):
# Create a complex matrix set.seed(10000) # Create a matrix mat <- matrix(rnorm(16),nrow = 4) # Solve this matrix print("The inverse matrix: ") solve(mat)
 "The inverse matrix: " [,1] [,2] [,3] [,4] [1,] -36.536944 2.6335609 23.357741 3.3006428 [2,] -4.128077 -0.1301276 3.954233 0.3871201 [3,] -12.332008 1.1835330 8.443213 0.9982597 [4,] -6.468463 0.6006657 3.255613 0.1099143
And here is the end of this post. We hope you use the solve () in R proficiently. If you have any questions, please leave a comment below. We will answer as possible.
Have a great day!
Maybe you are interested:
- Use Average Function In R On Different Data Sources
- How To Curve Function In R To Create Plots
- The exp() function in R
Name of the university: HCMUS