Code Explanation:
1) Importing PyTorch
import torch
Loads the PyTorch library.
Gives access to tensors and mathematical operations like matrix multiplication.
2) Creating the First Tensor
a = torch.tensor([[1,2],[3,4]])
Defines a 2×2 tensor a.
Internally stored as a matrix:
a=[1 2
3 4]
3) Creating the Second Tensor
b = torch.tensor([[5,6],[7,8]])
Defines another 2×2 tensor b.
b=[5 6
7 8]
4) Matrix Multiplication
c = torch.matmul(a, b)
Performs matrix multiplication (not element-wise).
5) Converting to List & Printing
print(c.tolist())
.tolist() converts the tensor into a standard Python nested list.
Prints the matrix result in list format.
Final Output
[[19, 22], [43, 50]]
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment