Matrix multiplication(dot product) - using numpy.ndarray with Example

Overview:

  • To multiply two matrices A and B the matrices need not be of same shape. For example, a matrix of shape 3x2 and a matrix of shape 2x3 can be multiplied, resulting in a matrix shape of 3 x 3.

 

  • Matrix multiplication is not commutative.

 

  • Two matrices can be multiplied using the dot() method of numpy.ndarray which returns the dot product of two matrices.

 

Example:

import numpy as np

import random

 

# Populate a 2 dimensional ndarray with random numbers between 2 to 10

def FillMatrix(matrix_in):

for x in range(0, matrix_in.shape[0]):

for y in range(0, matrix_in.shape[1]):

matrix_in[x][y] = random.randrange(2, 10) + 2

 

# Create a matrix1

matrix1 = np.ndarray((3,3))

matrix2 = np.ndarray((3,3))

 

# Dot product of two matrices using ndarray

newmatrix = matrix1.dot(matrix2)

 

# Print the Matrices

print("Matrix multiplication using numpy ndarray - Matrix 1:")

print("Matrix multiplication using numpy ndarray - Matrix 2:")

print("Matrix multiplication using numpy ndarray - Multiplication results:")

 

Output:

Matrix multiplication using numpy ndarray - Matrix 1:

[[ 10.   5.   4.]

 [  5.   7.  11.]

 [  4.  11.   4.]]

Matrix multiplication using numpy ndarray - Matrix 2:

[[  6.  11.   6.]

 [  4.   5.   6.]

 [ 10.   8.   6.]]

Matrix multiplication using numpy ndarray - Multiplication results:

[[ 120.  167.  114.]

 [ 168.  178.  138.]

[ 108.131.114.]]

 


Copyright 2024 © pythontic.com