To find the inverse of a matrix in R, you can use the solve()
function. This function takes a matrix as input and returns its inverse, provided the matrix is square and non-singular.
In this example,
matrix1
using the matrix()
function with a vector of values c(4, 7, 2, 6)
and specify the number of rows as 2.solve()
function on matrix1
and store the result in a variable called inverseMatrix1
.solve()
function computes the inverse of the matrix if it exists.print()
function to display the inverse matrix stored in inverseMatrix1
.matrix1 <- matrix(c(4, 7, 2, 6), nrow = 2)
inverseMatrix1 <- solve(matrix1)
print(inverseMatrix1)
[,1] [,2] [1,] 0.6 -0.7 [2,] -0.2 0.4
In this example,
matrix2
using the matrix()
function with a vector of values c(1, 2, 3, 0, 1, 4, 5, 6, 0)
and specify the number of rows as 3.solve()
function on matrix2
and store the result in a variable called inverseMatrix2
.solve()
function computes the inverse of the matrix if it exists.print()
function to display the inverse matrix stored in inverseMatrix2
.matrix2 <- matrix(c(1, 2, 3, 0, 1, 4, 5, 6, 0), nrow = 3)
inverseMatrix2 <- solve(matrix2)
print(inverseMatrix2)
[,1] [,2] [,3] [1,] -24 20 -5 [2,] 5 -4 1 [3,] 4 -3 1
In this example,
matrix3
using the diag()
function with a value of 2.solve()
function on matrix3
and store the result in a variable called inverseMatrix3
.solve()
function computes the inverse of the matrix if it exists.print()
function to display the inverse matrix stored in inverseMatrix3
.matrix3 <- diag(2)
inverseMatrix3 <- solve(matrix3)
print(inverseMatrix3)
[,1] [,2] [1,] 1 0 [2,] 0 1
In this tutorial, we learned How to find Inverse of a Matrix in R language with well detailed examples.