PyTorch torch.linalg.solve Function
PyTorch torch Reference Manual
torch.linalg.solveis a function in the PyTorch linear algebra module used to solve linear equations. It solves AX = B.
Function Definition
torch.linalg.solve(A, B, left=True, out=None)
Parameters:
A(Tensor): Coefficient matrix.B(Tensor): Right-hand side matrix or vector.left(bool, optional): If True, solves AX = B; otherwise solves XA = B. Default is True.out(Tensor, optional): Output tensor.
Return value:
torch.Tensor: Returns the solution of the linear equations.
Usage Example
Example
import torch
# Create coefficient matrix and right-hand side vector
A = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
B = torch.tensor([5.0, 11.0])
# Solve AX = B
X = torch.linalg.solve(A, B)
print("Coefficient matrix A:")
print(A)
print("nRight-hand side vector B:")
print(B)
print("nSolution X:")
print(X)
print("nVerification: A @ X =")
print(A @ X)
# Create coefficient matrix and right-hand side vector
A = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
B = torch.tensor([5.0, 11.0])
# Solve AX = B
X = torch.linalg.solve(A, B)
print("Coefficient matrix A:")
print(A)
print("nRight-hand side vector B:")
print(B)
print("nSolution X:")
print(X)
print("nVerification: A @ X =")
print(A @ X)
The output result is:
系数矩阵 A:
tensor([[1., 2.],
[3., 4.]])
右侧向量 B:
tensor([ 5., 11.])
解 X:
tensor([1., 2.])
验证: A @ X =
tensor([ 5., 11.])
Other Extensions