## R – Inverse Matrix

To inverse a given matrix in R, call solve() function, and pass given matrix as argument to it. The function returns the inverse of the supplied matrix.

In this tutorial, we will learn how to inverse a Matrix using solve() function, with the help of examples.

### Syntax

The syntax of solve() function is

`solve(x)`

where

Return Value

solve() function returns a matrix.

### Examples

In the following program, we will create a matrix `A` and find Inverse Matrix of `A` using solve() function.

example.R

```data <- c(1, 4, 0, -1, 0, 1, 2, 6, -1)
A <- matrix(data, nrow = 3, ncol = 3)

A_I <- solve(A)

print("Matrix A")
print(A)
print("Inverse Matrix of A")
print(A_I)```

Output

```[1] "Matrix A"
[,1] [,2] [,3]
[1,]    1   -1    2
[2,]    4    0    6
[3,]    0    1   -1
[1] "Inverse Matrix of A"
[,1] [,2] [,3]
[1,]    3 -0.5    3
[2,]   -2  0.5   -1
[3,]   -2  0.5   -2```

Now, let us take a matrix of different dimensions, say 2×2, and find its transpose.

example.R

```data <- c(1, 2, 1, -2)
A <- matrix(data, nrow = 2, ncol = 2)

A_I <- solve(A)

print("Matrix A")
print(A)
print("Inverse Matrix of A")
print(A_I)```

Output

```[1] "Matrix A"
[,1] [,2]
[1,]    1    1
[2,]    2   -2
[1] "Inverse Matrix of A"
[,1]  [,2]
[1,]  0.5  0.25
[2,]  0.5 -0.25```

Inverse of an Identity Matrix is Identity Matrix itself. Let us verify that programmatically using the following program.

example.R

```data <- c(1, 0, 0, 1)
A <- matrix(data, nrow = 2, ncol = 2)

A_I <- solve(A)

print("Matrix A")
print(A)
print("Inverse Matrix of A")
print(A_I)```

Output

```[1] "Matrix A"
[,1] [,2]
[1,]    1    0
[2,]    0    1
[1] "Inverse Matrix of A"
[,1] [,2]
[1,]    1    0
[2,]    0    1```

Also inverse of an inverse matrix results in the original matrix. Let us verify that programmatically using solve() function.

example.R

```data <- c(1, 2, 1, -1)
A <- matrix(data, nrow = 2, ncol = 2)

A_I_I <- solve(solve(A))

print("Matrix A")
print(A)
print("Inverse Matrix of (Inverse A)")
print(A_I_I)```

Output

```[1] "Matrix A"
[,1] [,2]
[1,]    1    1
[2,]    2   -1
[1] "Inverse Matrix of (Inverse A)"
[,1] [,2]
[1,]    1    1
[2,]    2   -1```

### Conclusion

In this R Tutorial, we learned how to Inverse a Matrix in R using solve() function, with the help of examples.