NumPy - Create a 3x3 identity matrix

By IncludeHelp Last updated : December 16, 2023

Problem statement

Write a Python program to Create a 3x3 identity matrix using NumPy.

Prerequisites

To understand the given solution, you should know about the following Python topics:

What is a 3x3 identity matrix?

A 3x3 identity matrix is a square array of 3 rows and 3 columns with ones on the main diagonal. The below is an identity matrix of 3x3:

[[1.,  0.,  0.],
 [0.,  1.,  0.],
  [0.,  0.,  1.]]

Creating a 3x3 identity matrix

To create a 3x3 identity matrix, use numpy.identity() method and pass 3 as its argument. The numpy.identity() method is a library method of the numpy module which returns the identity array (matrix) based on the given value of n.

Below is the syntax of numpy.identity() method:

numpy.identity(n, dtype=None, *, like=None)

Here, n is the number of rows and columns to get a nxn identity matrix. The other two parameters dtype and like are options, dtype specifies the data type, and like specifies the reference object to allow the creation of arrays that are not NumPy arrays.

Python program to create a 3x3 identity matrix

Create and print a 3x3 identity matrix.

# Importing numpy library
import numpy as np

# By using the numpy.identity() method
# Creating a 3x3 identity matrix
identity_matrix = np.identity(3)

# Printing the 3x3 identity matrix
print("The 3x3 identity matrix is :")
print(identity_matrix)

Output

The output of the above program is:

The 3x3 identity matrix is :
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

Code Explanation

  • To use NumPy in the program, we imported the numpy module.
  • Create a 3x3 identity matrix by using the np.identity() method ans stored into identity_matrix variable. Here, we used 3 as the value of n. Thus, it will be a 3x3 square array with ones on the main diagonal.
  • Finally, printed identity_matrix.

Python program to create a 3x3 identity matrix of bool types

Create and print a 3x3 identity matrix with bool values (TRUE and FALSE).

# Importing numpy library
import numpy as np

# By using the numpy.identity() method
# Creating a 3x3 identity matrix
identity_matrix = np.identity(3, dtype='bool')

# Printing the 3x3 identity matrix
print("The 3x3 identity matrix is :")
print(identity_matrix)

Output

The output of the above program is:

The 3x3 identity matrix is :
[[ True False False]
 [False  True False]
 [False False  True]]

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.