Skip to main content

Posts

Showing posts from October, 2019

Numpy : Matrix multiplication using Arrays & Matrices

Numpy, one of the powerful package in Python has Matrices and N-Dimensional Arrays which can be used for matrix computation. Numpy matrices are basically 2-dimensional arrays, which are subclassed from ndarray having access to all attributes and methods of the super class. Numpy arrays, on the otherhand are N-Dimensional arrays. For numpy matrices, if we need to obtain matrix multiplication, we will simply use "*" operator. import numpy as np a=np.mat('4 3; 2 1') b=np.mat('1 2; 3 4') print(a) # [[4 3] # [2 1]] print(b) # [[1 2] # [3 4]] print(a*b) # [[13 20] # [ 5 8]] However, if we use "*" operator on Numpy arrays, we will get the element-wise multiplication import numpy as np c=np.array([[4, 3], [2, 1]]) d=np.array([[1, 2], [3, 4]]) print(c*d) # [[4 6] # [6 4]] To obtain the matrix multiplication using Numpy arrays, we need to do the following print(np.dot(c,d)) # [[13 20] # [ 5 8]] # OR print(a@b) # [[13 20] # [ 5