NumPy Matrix Multiplication

PythonPythonBeginner
Practice Now

Introduction

NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions. In this lab, we will cover the concept of Multiplication of two Matrix in the NumPy library.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Importing Required Libraries

import numpy as np

Defining Matrices

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:\n", A)
print("Matrix B:\n", B)

Using multiply() Function

print("Element-wise multiplication of matrix A and B:")
print(np.multiply(A, B))

Using matmul() Function

print("Matrix multiplication of matrix A and B:")
print(np.matmul(A, B))

Using dot() Function

print("Dot product of matrix A and B:")
print(np.dot(A, B))

Using All Three Methods

print("Matrix multiplication of matrix A and B using all three methods:")
print("Using 'multiply()':")
print(np.multiply(A, B))
print("Using 'matmul()':")
print(np.matmul(A, B))
print("Using 'dot()':")
print(np.dot(A, B))

Summary

In this lab, we learned about the concept of matrix multiplication in the NumPy library. We covered the three ways of matrix multiplication such as multiply(), matmul() and dot() functions with the help of examples. These functions are capable of performing different operations such as element-wise multiplication, matrix multiplication and scalar or dot product of two matrices.

Other Python Tutorials you may like