INV
Computes the matrix A^{-1} such that AA^{-1} = I, where I is the identity matrix. The input matrix must be square and non-singular. For solving linear systems, using solve is generally more efficient and stable than computing an explicit inverse.
Excel Usage
=INV(matrix)
matrix(list[list], required): Square 2D array of numeric values to invert.
Returns (list[list]): 2D array representing the matrix inverse.
Example 1: Inverse of 2x2 matrix
Inputs:
| matrix | |
|---|---|
| 1 | 2 |
| 3 | 4 |
Excel formula:
=INV({1,2;3,4})
Expected output:
| Result | |
|---|---|
| -2 | 1 |
| 1.5 | -0.5 |
Example 2: Inverse of diagonal 3x3 matrix
Inputs:
| matrix | ||
|---|---|---|
| 2 | 0 | 0 |
| 0 | 4 | 0 |
| 0 | 0 | 0.5 |
Excel formula:
=INV({2,0,0;0,4,0;0,0,0.5})
Expected output:
| Result | ||
|---|---|---|
| 0.5 | 0 | 0 |
| 0 | 0.25 | 0 |
| 0 | 0 | 2 |
Example 3: Inverse of identity matrix
Inputs:
| matrix | |
|---|---|
| 1 | 0 |
| 0 | 1 |
Excel formula:
=INV({1,0;0,1})
Expected output:
| Result | |
|---|---|
| 1 | 0 |
| 0 | 1 |
Example 4: Inverse of matrix with negative entries
Inputs:
| matrix | |
|---|---|
| -2 | 1 |
| 5 | 3 |
Excel formula:
=INV({-2,1;5,3})
Expected output:
| Result | |
|---|---|
| -0.272727 | 0.0909091 |
| 0.454545 | 0.181818 |
Python Code
import numpy as np
from scipy.linalg import inv as scipy_inv
def inv(matrix):
"""
Compute the inverse of a square matrix.
See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.inv.html
This example function is provided as-is without any representation of accuracy.
Args:
matrix (list[list]): Square 2D array of numeric values to invert.
Returns:
list[list]: 2D array representing the matrix inverse.
"""
try:
def to2d(x):
return [[x]] if not isinstance(x, list) else x
matrix = to2d(matrix)
if not isinstance(matrix, list) or not matrix or not all(isinstance(row, list) for row in matrix):
return "Error: matrix must be a non-empty 2D list"
n = len(matrix)
if any(len(row) != n for row in matrix):
return "Error: matrix must be square (n x n)"
try:
a = np.array(matrix, dtype=float)
except (ValueError, TypeError):
return "Error: matrix entries must contain numeric values"
if not np.all(np.isfinite(a)):
return "Error: matrix must contain only finite numbers"
try:
res = scipy_inv(a)
except np.linalg.LinAlgError:
return "Error: Matrix is singular and cannot be inverted"
except Exception as e:
return f"Error: {str(e)}"
return res.tolist()
except Exception as e:
return f"Error: {str(e)}"Online Calculator
Square 2D array of numeric values to invert.