PyTorch torch.linalg.matrix_power Function
Pytorch torch Reference Manual
torch.linalg.matrix_powerIt is a function in the PyTorch linear algebra module used to compute matrix powers. It computes the n-th power of a matrix, A^n.
Function Definition
torch.linalg.matrix_power(A, n, out=None)
Parameters:
A(Tensor): Input square matrix.n(int): The power, which can be an integer, zero, or negative number.out(Tensor, optional): 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 A to the power of 2
A_power_2 = torch.linalg.matrix_power(A, 2)
print("Matrix A:")
print(A)
print("nA^2:")
print(A_power_2)
print("n verification: A @ A =")
print(A @ A)
# Create a matrix
A = torch.tensor([[1.0, 2.0],
[3.0, 4.0]])
# Compute A to the power of 2
A_power_2 = torch.linalg.matrix_power(A, 2)
print("Matrix A:")
print(A)
print("nA^2:")
print(A_power_2)
print("n verification: A @ A =")
print(A @ A)
The output result 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)
print("A^0:")
print(torch.linalg.matrix_power(A, 0))
# A^-1 = the inverse matrix of A
print("nA^-1:")
print(torch.linalg.matrix_power(A, -1))
A = torch.tensor([[1.0, 2.0],
[3.0, 4.0]], dtype=torch.float64)
# A^0 = I (identity matrix)
print("A^0:")
print(torch.linalg.matrix_power(A, 0))
# A^-1 = the inverse matrix of A
print("nA^-1:")
print(torch.linalg.matrix_power(A, -1))
Other Extensions