Table of Contents
Shortcuts

# torch.linalg.inv

torch.linalg.inv(A, *, out=None) → Tensor

  Computes the inverse of a square matrix if it exists. Throws a RuntimeError if the matrix is not invertible.

  Letting K\mathbb{K}K be R\mathbb{R}R or C\mathbb{C}C, for a matrix A∈K n×n A \in \mathbb{K}^{n \times n}A∈K n×n, its inverse matrix A−1∈K n×n A^{-1} \in \mathbb{K}^{n \times n}A−1∈K n×n (if it exists) is defined as

  A−1 A=A A−1=I n A^{-1}A = AA^{-1} = \mathrm{I}_n A−1 A=A A−1=I n​

  where I n\mathrm{I}_n I n​ is the n-dimensional identity matrix.

  The inverse matrix exists if and only if A A A is invertible. In this case, the inverse is unique.

  Supports input of float, double, cfloat and cdouble dtypes. Also supports batches of matrices, and if `A` is a batch of matrices then the output has the same batch dimensions.

  Note

  When inputs are on a CUDA device, this function synchronizes that device with the CPU.

  Note

  Consider using `torch.linalg.solve()` if possible for multiplying a matrix on the left by the inverse, as:

      linalg.solve(A, B) == linalg.inv(A) @ B  # When B is a matrix

  It is always preferred to use `solve()` when possible, as it is faster and more numerically stable than computing the inverse explicitly.

  See also

  `torch.linalg.pinv()` computes the pseudoinverse (Moore-Penrose inverse) of matrices of any shape.

  `torch.linalg.solve()` computes `A`.inv() @ `B` with a numerically stable algorithm.

  Parameters:

    A (Tensor) – tensor of shape (*, n, n) where * is zero or more batch dimensions consisting of invertible matrices.

  Keyword Arguments:

    out (Tensor, optional) – output tensor. Ignored if None. Default: None.

  Raises:

    RuntimeError – if the matrix `A` or any matrix in the batch of matrices `A` is not invertible.

  Examples:

      >>> A = torch.randn(4, 4)
      >>> Ainv = torch.linalg.inv(A)
      >>> torch.dist(A @ Ainv, torch.eye(4))
      tensor(1.1921e-07)

      >>> A = torch.randn(2, 3, 4, 4)  # Batch of matrices
      >>> Ainv = torch.linalg.inv(A)
      >>> torch.dist(A @ Ainv, torch.eye(4))
      tensor(1.9073e-06)

      >>> A = torch.randn(4, 4, dtype=torch.complex128)  # Complex matrix
      >>> Ainv = torch.linalg.inv(A)
      >>> torch.dist(A @ Ainv, torch.eye(4))
      tensor(7.5107e-16, dtype=torch.float64)

## Docs

Access comprehensive developer documentation for PyTorch

View Docs

## Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

## Resources

Find development resources and get your questions answered

View Resources

To analyze traffic and optimize your experience, we serve cookies on this site. By clicking or navigating, you agree to allow our usage of cookies. As the current maintainers of this site, Facebook’s Cookies Policy applies. Learn more, including about available controls: Cookies Policy.