PyTorch torch.linalg.matrix_power function
PyTorch torch reference manual
torch.linalg.matrix_power is a function in PyTorch's linear algebra module used to compute matrix powers. It computes the n-th power A^n of a matrix.
Function definition
torch.linalg.matrix_power(A, n, out=None)
Parameters:
A(Tensor): Input square matrix.n(int): The exponent, which can be an integer, zero, or a negative number.out(Tensor, optional): the output tensor.
Return Value:
torch.Tensor: Returns the n-th power of the matrix.
Usage examples
Example
import
torch
Create a matrix
A
=
torch.
tensor
(
[
[
1.0
,
2.0
]
,
[
3.0
,
4.0
]
]
)
Compute the 2nd power of A
A_power_2
=
torch.
linalg
.
matrix_power
(
A
,
2
)
(
"Matrix A:"
)
(
A
)
(
"nA^2:"
)
(
A_power_2
)
(
"nVerify: A @ A ="
)
(
A
@
A
)
The output is:
矩阵 A:
tensor([[1., 2.],
[3., 4.]])
A^2:
tensor([[ 7., 10.],
[15., 22.]])
验证: A @ A =
tensor([[ 7., 10.],
[15., 22.]])
Example - A^0 and A^-1
import
torch
A
=
torch.
tensor
(
[
[
1.0
,
2.0
]
,
[
3.0
,
4.0
]
]
,
dtype
=
torch.
float64
)
A^0 = I (identity matrix)
(
"A^0:"
)
(
torch.
linalg
.
matrix_power
(
A
,
0
)
)
A^-1 = the inverse of A
(
"nA^-1:"
)
(
torch.
linalg
.
matrix_power
(
A
,
1
)
)