Signup/Sign In

NumPy Matrix Multiplication

In this tutorial, we will cover the concept of Multiplication of two Matrix in the NumPy library. Also, as the NumPy library is mainly used for manipulation and array-processing, so this is a very important concept.

In NumPy, the Multiplication of matrix is basically an operation where we take two matrices as input and multiply rows of the first matrix to the columns of the second matrix, producing a single matrix as the output. But there is an important thing that we have to ensure, that is the number of rows in the first matrix should be equal to the number of columns in the second matrix.

The process of multiplication of matrix in Numpy is commonly known as Vectorization. The main goal of the vectorization process is to reduce the use of for loops for carrying out such operations. And when the usage of for loop is skipped from the program it will reduce the overall execution time of the code.

Let us show you an image of the Matrix Multiplication and then we will move on to different ways of Matrix Multiplication:

Numpy Matrix multiplication

Different ways for Matrix Multiplication

Mainly there are three different ways of Matrix Multiplication in the NumPy and these are as follows:

  • Using the multiply() Function
    This function will return the element-wise multiplication of two given arrays.

  • Using the matmul() Function
    This function will return the matrix product of the two input arrays.

  • Using the dot() Function
    This function will return the scalar or dot product of two given arrays.

Now we will understand each of the above-given way in detail, one by one.

1. Using multiply() Function

The numpy.multiply() function is used when we want to do the multiplication of two arrays. This method will return the product of arr1 and arr2 with the multiplication done element-wise.

If, matrix A is:

matrix multiplication example numpy

and, matrix B is:

matrix multiplication example numpy

then, A*B will be computed like this:

matrix multiplication example numpy

Syntax of numpy.multiply():

The syntax required to use this function is as follows:

numpy.multiply(arr1, arr2, /, out, *, where, casting, order, dtype=None, subok=True[, signature, extobj], ufunc ‘multiply’)

Let us discuss the above-given parameters:

  • arr1
    This parameter is used to indicate the 1st input array.

  • arr2
    This parameter is used to indicate the 2nd nput array.

  • dtype
    This parameter is used to indicate the type of the returned array.

  • out
    This parameter mainly specifies the location into which the result is stored.

    • If this parameter is provided then it must have a shape which can store the result of the multiplication.

    • If this parameter is either not provided or None, in that case a freshly-allocated array will be returned.

  • where
    In this parameter, the True value indicates to calculate the ufunc at that position and in case of False value, leaves the value in the output alone.

  • **kwargs
    This parameter allows passing key-value pair to the function.

Basic Example:

Below we have a code snippet covering the multiply() function that is used for matrix multiplication in NumPy:

import numpy as np  

a = np.array([[11,2,23],[14,75,6],[17,8,9]], ndmin=3) 
print("A is:\n",a)

b = np.array([[9,8,7],[6,5,4],[3,2,1]], ndmin=3)    
print("B is:\n",b)

out = np.multiply(a,b)  
print("The resultant matrix is :")
print(out)

The output of the above code will be:

numpy multiply() function code example

2. Using matmul() Function

The matmul() function in the NumPy library is used to return the matrix product of two given arrays.

If, matrix A is:

numpy matmul() function code example

and, matrix B is:

numpy matmul() function code example

then, A*B using matmul() function will be calculated like this:

numpy matmul() function example

Syntax for matmul():

The syntax required to use this function is as follows:

np.matmul(array a, array b)

It is important to note that while it returns a normal product for 2-D arrays, if dimensions of either of the given array is >2 then it is treated as a stack of matrices residing in the last two indexes and is broadcast accordingly. And on the other hand, if either argument is a 1-D array then it is promoted to a matrix by appending a 1 to its dimension, which is removed after multiplication.

Example 1:

In the example below, we have used the matmul() function for matrix multiplication:

import numpy as np

A = np.array([[1,2,3], [4,5,6],[1,2,1]])
B = np.array([[1,1,1], [0,1,0], [1,1,1]])

print("Matrix A is:\n",A)
print("Matrix A is:\n",B)

C = np.matmul(A,B)
print("The Matrix multiplication of matrix A and B is:\n",C)

The output of the above code will be:

numpy matmul() function code example

Example 2:

Let's take another example in which the two arrays(matrix) being multiplied are of different dimensions:

import numpy.matlib 
import numpy as np 

a = [[1,4],[2,1]] 
print("A is",a)
b = [1,2]
print("B is",b)
print("AxB is")
print(np.matmul(a,b))
print("BxA is ")
print (np.matmul(b,a))


A is [[1, 4], [2, 1]]
B is [1, 2]
AxB is
[9 4]
BxA is
[5 6]

3. Using dot() function

The dot product of any two given matrices using dot() function in the NumPy library is basically their matrix product. The only major difference is that in dot product we can have scalar values as well. Thus dot product of two matrices is also known as Scalar product.

Syntax of numpy.dot():

The syntax required to use this function is as follows:

numpy.dot(a, b, out=None)

If, matrix A is:

numpy dot() function example

and matrix B is,

numpy dot() function example

The dot product of A and B is calculated as:

A.B = a11*b11 + a12*b12 + a13*b13

Now let's take a few code examples to see this in action.

Example 1:

With the example given below we will illustrate dot product of two 1-D Matrices:

import numpy as np

A = np.array([7,9,8])
B = np.array([2,5,6])
print("Matrix A is:\n", A)
print("Matrix A is:\n", B)

C = np.dot(A,B)
print("Dot product of matrix A and B is:\n", C)


Matrix A is:
[7 9 8]
Matrix A is:
[2 5 6]
Dot product of matrix A and B is:
107

Example 2:

In the example given below we will illustrate dot product of two 2-D Matrices:

import numpy as np

A = np.array([[1,4],[3,1]])
B = np.array([[4,5],[6,5]])
print("Matrix A is:\n", A)
print("Matrix A is:\n", B)

C = np.dot(A, B)
print("Matrix multiplication of matrix A and B is:\n", C)

numpy dot() function code example

Example 3:

In the example given below we will illustrate dot product of a scalar value and a 2-D Matrices:

A = np.array([[2,4],[3,5]])
print("Matrix A is:\n", A)
C = np.dot(3, A)
print("Matrix multiplication of matrix A with scalar :\n", C)

numpy dot() function code example

Summary

In this tutorial,we covered different ways of Matrix Mutiplication. We covered multiply() function, matmul() function and dot() function with their syntax along with multiple code examples for each of these functions.



About the author:
Aspiring Software developer working as a content writer. I like computer related subjects like Computer Networks, Operating system, CAO, Database, and I am also learning Python.