Implementation of Identity Matrix in Python

             Identify Matrix has the rows and columns in equal manner. It has ones on the diagonal and zeros in other places.

This can be done two different ways as follows…

  • ·       Using Numpy
  • ·       Using Plain Python Code

1.Using Numpy:

              This method uses the ‘Numpy’ to create object and calling built-in functions.

Implementation:

  • ·       It uses Numpy built-in file and creates the object. It calls the ‘identity()’ function to build the identity matrix.
  • ·       Finally,prints the identity matrix.

Code:

#Using Numpy

import numpy as np1

# Create a 4x4 identity matrix

I = np1.identity(4)

print("Here is the Identity Matrix using Numpy:")

print(I)

Output:

Here is the Identity Matrix using Numpy:

[[1. 0. 0. 0.]

 [0. 1. 0. 0.]

 [0. 0. 1. 0.]

 [0. 0. 0. 1.]]

2.Using Plain Python Code:

              This is the second method to generate the Identity Matrix. It uses loops and lists.

Implementation:

Method 1: Uses Loops

# User Defined Function to create an identity matrix

def identity_matrix(no):

    I = []

    for i in range(no):

        row = []

        for j in range(no):

            if i == j:

                row.append(1)

            else:

                row.append(0)

        I.append(row)

    return I

# 3x3 identity matrix Generation

s_matrix = identity_matrix(3)

print("Here is the Identity Matrix:")

for row in s_matrix:

    print(row)

Output:

Here is the Identity Matrix:

[1, 0, 0]

[0, 1, 0]

[0, 0, 1]

Method2 :Uses List

#Using Loops

no = 6

I = [[1 if i == j else 0 for j in range(no)] for i in range(no)]

print("Here is the Identity Matrix:")

for row in I:

    print(row)

Output:

Here is the Identity Matrix:

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

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

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

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

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

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

These are the various methods to generate Identity matrix in Python with and without Numpy. Hope, you understood the concepts. Keep Coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

Employee record management in C

Datatypes and Variables in java script