Q:

pytorch - matrix multiplication

# Program to multiply two matrices using nested loops

# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
         [0,0,0,0],
         [0,0,0,0]]

# iterate through rows of X
for i in range(len(X)):
   # iterate through columns of Y
   for j in range(len(Y[0])):
       # iterate through rows of Y
       for k in range(len(Y)):
           result[i][j] += X[i][k] * Y[k][j]

for r in result:
   print(r)
1
# We need install numpy in order to import it 
import numpy as np 
  
# input two matrices 
mat1 = ([1, 6, 5],[3 ,4, 8],[2, 12, 3]) 
mat2 = ([3, 4, 6],[5, 6, 7],[6,56, 7]) 
  
# This will return dot product 
res = np.dot(mat1,mat2) 
  
  
# print resulted matrix 
print(res) 
0
# Program to multiply two matrices (vectorized implementation) 
  
# Program to multiply two matrices (vectorized implementation) 
import numpy as np 
# take a 3x3 matrix 
A = [[12, 7, 3], 
    [4, 5, 6], 
    [7, 8, 9]] 
  
# take a 3x4 matrix 
B = [[5, 8, 1, 2], 
    [6, 7, 3, 0], 
    [4, 5, 9, 1]] 
  
# result will be 3x4 
  
result= [[0,0,0,0], 
        [0,0,0,0], 
        [0,0,0,0]] 
  
result = np.dot(A,B) 
  
for r in result: 
    print(r) 
0
# Matrix multiplication
a  = torch.tensor([[0, 2, 4], [1, 3, 5]])
b  = torch.tensor([[0, 7], [8, 9], [10, 11]])
torch.mm(a, b)
0
>>> a = np.array([[ 5, 1 ,3], 
                  [ 1, 1 ,1], 
                  [ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])
-1

New to Communities?

Join the community