How to multiply matrices in NumPy: multiply(), matmul()

What is NumPy?

NumPy is a Python library that allows the creation of multidimensional arrays, as well as various operations on them, including matrix addition, subtraction, and multiplication.

What is a matrix?

In mathematics, a matrix is ​​a set of numbers arranged in rows and columns in which each element can be identified by the row and column number it occupies within it.

How to install NumPy in Python?

Once you have Python installed on your PC, open Command Prompt. To do this, press Windows + R, type CMD and press Enter.

In the window that opens, run the following code:

pip install numpy

How to multiply matrices in NumPy?

NumPy mainly offers 2 functions for matrix multiplication: multiply() and matmul().

Element-wise matrix multiplication with multiply()

NumPy’s np.multiply() function performs element-wise multiplication of two matrices. It requires as parameters only the variables assigned to both matrices.

Code:

import numpy as np
a=np.array([[1,2],
            [3,4]])
b=np.array([[5,6],
            [7,8]])
c=np.multiply(a,b)
print("Element-wise matrix multiplication: ", c)

Result:

The product of two matrices with matmul()

The np.matmul() function performs the typical matrix multiplication in mathematics, so care must be taken that the number of columns in the first matrix is ​​equal to the number of rows in the second.

The function requires as parameters the variables assigned to both arrays.

Code:

import numpy as np
a=np.array([[1,2],
            [3,4]])
b=np.array([[5,6],
            [7,8]])
c=np.matmul(a,b)
print("Product of two matrices a and b: ", c)

Result:

Leave a Comment

Scroll to Top