Related Articles

Related Articles

Generate a matrix product of two NumPy arrays
  • Last Updated : 29 Aug, 2020

We can multiply two matrices with the function np.matmul(a,b). When we multiply two arrays of order (m*n) and  (p*q ) in order to obtained matrix product then its output contains m rows and q columns where n is n==p is a necessary condition.

Syntax: numpy.matmul(x1, x2, /, out=None, *, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj]) 

To multiply two matrices take the row from first array and column of second array and multiply the corresponding elements. Then add the value for the final answer. Suppose there are two matrices A and B.

A = [[A00, A01],
     [A10, A11]]
     
B = [[B00, B01],
     [B10, B11]]

Then the product is calculated as shown below
A*B = [[(A00*B00 + A01*B10), (A00*B01 + A01*B11)],
       [(A10*B00 + A11+B10), (A10*B01 + A11*B11)]]

Below is the implementation.

Python3



filter_none

edit
close

play_arrow

link
brightness_4
code

# Importing Library
import numpy as np
  
# Finding the matrix product
arr1 = np.array([[1, 2, 3], [4, 5, 6],
                 [7, 8, 9]])
arr2 = np.array([[11, 12, 13], [14, 15, 16],
                 [17, 18, 19]])
  
matrix_product = np.matmul(arr1, arr2)
print("Matrix Product is ")
print(matrix_product)
print()
  
arr1 = np.array([[2,2],[3,3]])
arr2 = np.array([[1,2,3],[4,5,6]])
  
matrix_product = np.matmul(arr1, arr2)
print("Matrix Product is ")
print(matrix_product)
print()
  
arr1 = np.array([[100,200],[300,400]])
arr2 = np.array([[1,2],[4,6]])
  
matrix_product = np.matmul(arr1, arr2)
print("Matrix Product is ")
print(matrix_product)

chevron_right


Output:

Matrix Product is 
[[ 90  96 102]
 [216 231 246]
 [342 366 390]]

Matrix Product is 
[[10 14 18]
 [15 21 27]]

Matrix Product is 
[[ 900 1400]
 [1900 3000]]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :