Open In App

Parallel matrix-vector multiplication in NumPy

In this article, we will discuss how to do matrix-vector multiplication in NumPy.

Matrix multiplication with Vector

For a matrix-vector multiplication, there are certain important points:



# a and b are matrices
prod = numpy.matmul(a,b)

For matrix-vector multiplication, we will use np.matmul() function of NumPy, we will define a 4 x 4 matrix and a vector of length 4.






import numpy as np
  
a = np.array([[1, 2, 3, 13],
              [4, 5, 6, 14],
              [7, 8, 9, 15],
              [10, 11, 12, 16]])
  
b = np.array([10, 20, 30, 40])
  
print("Matrix a =", a)
print("Matrix b =", b)
print("Product of a and b =",
      np.matmul(a, b))

Output:

Matrix multiplication with another Matrix

We use the dot product to do matrix-matrix multiplication. We will use the same function for this also.

prod = numpy.matmul(a,b)  # a and b are matrices

For a matrix-matrix multiplication, there are certain important points:

We will define two 3 x 3 matrix:




import numpy as np
  
a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
  
b = np.array([[11, 22, 33],
              [44, 55, 66],
              [77, 88, 99]])
  
print("Matrix a =", a)
print("Matrix b =", b)
print("Product of a and b =", np.matmul(a, b))

Output:


Article Tags :