Invert a numeric or complex matrix.

inv(a)

Arguments

a

real or complex square matrix

Details

Computes the matrix inverse by calling solve(a) and catching the error if the matrix is nearly singular.

Value

square matrix that is the inverse of a.

Note

inv() is the function name used in Matlab/Octave.

See also

Examples

A <- hilb(6)
B <- inv(A)
B
#>       [,1]    [,2]     [,3]     [,4]     [,5]     [,6]
#> [1,]    36    -630     3360    -7560     7560    -2772
#> [2,]  -630   14700   -88200   211680  -220500    83160
#> [3,]  3360  -88200   564480 -1411200  1512000  -582120
#> [4,] -7560  211680 -1411200  3628800 -3969000  1552320
#> [5,]  7560 -220500  1512000 -3969000  4410000 -1746360
#> [6,] -2772   83160  -582120  1552320 -1746360   698544
# Compute the inverse matrix through Cramer's rule:
n <- nrow(A)
detA <- det(A) 
b <- matrix(NA, nrow = n, ncol = n)
for (i in 1:n) {
    for (j in 1:n) {
        b[i, j] <- (-1)^(i+j) * det(A[-j, -i]) / detA
    }
}
b
#>       [,1]    [,2]     [,3]     [,4]     [,5]     [,6]
#> [1,]    36    -630     3360    -7560     7560    -2772
#> [2,]  -630   14700   -88200   211680  -220500    83160
#> [3,]  3360  -88200   564480 -1411200  1512000  -582120
#> [4,] -7560  211680 -1411200  3628800 -3969000  1552320
#> [5,]  7560 -220500  1512000 -3969000  4410000 -1746360
#> [6,] -2772   83160  -582120  1552320 -1746360   698544