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 if
Ais a batch of matrices thenthe output has the same batch dimensions.If
n= 0, it returns the identity matrix (or batch) of the same shapeasA. Ifnis negative, it returns the inverse of each matrix(if invertible) raised to the power ofabs(n).Note
Consider using
torch.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 use
solve()when possible, as it is faster and morenumerically stable than computing explicitly.See also
torch.linalg.solve()computesA.inverse() @Bwith anumerically stable algorithm.- Parameters
- Keyword Arguments
out (Tensor,optional) – output tensor. Ignored ifNone. Default:None.
- Raises
RuntimeError – if
n< 0 and the matrixAor any matrix in the batch of matricesAis 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]]])