Rate this Page

torch.linalg.matrix_power#

torch.linalg.matrix_power(A,n,*,out=None)Tensor#

Computes then-th power of a square matrix for an integern.

Supports input of float, double, cfloat and cdouble dtypes.Also supports batches of matrices, and ifA is a batch of matrices thenthe output has the same batch dimensions.

Ifn= 0, it returns the identity matrix (or batch) of the same shapeasA. Ifn is negative, it returns the inverse of each matrix(if invertible) raised to the power ofabs(n).

Note

Consider usingtorch.linalg.solve() if possible for multiplying a matrix on the left bya negative power as, ifn> 0:

torch.linalg.solve(matrix_power(A,n),B)==matrix_power(A,-n)@B

It is always preferred to usesolve() when possible, as it is faster and morenumerically stable than computingAnA^{-n} explicitly.

See also

torch.linalg.solve() computesA.inverse() @B with anumerically stable algorithm.

Parameters
  • A (Tensor) – tensor of shape(*, m, m) where* is zero or more batch dimensions.

  • n (int) – the exponent.

Keyword Arguments

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

Raises

RuntimeError – ifn< 0 and the matrixA or any matrix in the batch of matricesA is not invertible.

Examples:

>>>A=torch.randn(3,3)>>>torch.linalg.matrix_power(A,0)tensor([[1., 0., 0.],        [0., 1., 0.],        [0., 0., 1.]])>>>torch.linalg.matrix_power(A,3)tensor([[ 1.0756,  0.4980,  0.0100],        [-1.6617,  1.4994, -1.9980],        [-0.4509,  0.2731,  0.8001]])>>>torch.linalg.matrix_power(A.expand(2,-1,-1),-2)tensor([[[ 0.2640,  0.4571, -0.5511],        [-1.0163,  0.3491, -1.5292],        [-0.4899,  0.0822,  0.2773]],        [[ 0.2640,  0.4571, -0.5511],        [-1.0163,  0.3491, -1.5292],        [-0.4899,  0.0822,  0.2773]]])