How to Apply the solve() Function in R (3 Examples)

In this R programming tutorial you’ll learn how to apply the solve() function to solve a system of equations.

Example 1: Applying solve() Function in R (Basics)

solve(2, 7)                                # Using solve
# 3.5

Example 2: Solving System of Equations

my_matrix_ex2_a <- matrix(c(15, 3,         # Left matrix
                            8, 4),
                          nrow = 2)
my_matrix_ex2_a                            # Returning matrix to console
#      [,1] [,2]
# [1,]   15    8
# [2,]    3    4
my_matrix_ex2_b <- matrix(c(22,            # Right matrix
                            6),
                          nrow = 2)
my_matrix_ex2_b                            # Returning matrix to console
#      [,1]
# [1,]   22
# [2,]    6
solve(my_matrix_ex2_a, my_matrix_ex2_b)    # Using solve
#           [,1]
# [1,] 1.1111111
# [2,] 0.6666667

Example 3: Returning Inverse of Matrix Using solve Function

set.seed(8654921)                          # Randomly create matrix
my_matrix_ex3 <- matrix(runif(16),
                        nrow = 4)
my_matrix_ex3                              # Returning matrix to console
#           [,1]      [,2]       [,3]      [,4]
# [1,] 0.1733941 0.8762532 0.38141699 0.4757218
# [2,] 0.6210905 0.2313376 0.90522556 0.7481271
# [3,] 0.2154532 0.3784298 0.49347240 0.0364312
# [4,] 0.1197730 0.7645092 0.04701281 0.3200175
solve(my_matrix_ex3)                       # Using solve
#             [,1]       [,2]       [,3]      [,4]
# [1,] -7.34470797  1.6138486  2.0580393  6.911174
# [2,] -0.04432789 -0.4827015  0.8147823  1.101585
# [3,]  3.06320317 -0.3790991  0.7113516 -3.748337
# [4,]  2.40479585  0.6048320 -2.8212478 -1.542802

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top