Home > Software design >  Error while creating Identity matrix using list in python
Error while creating Identity matrix using list in python

Time:01-09

I was trying to make an identity matrix to find the inverse. But I am stuck at this moment due to a bug in the code. A fresh eye would help a lot.

identity=[]
null=[]
for i in range(3):
    null.append(i*0)
for j in range(3):
    identity.append(null)
for k in range(3):
    identity[k][k]=1

print(identity)

The result I got

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

what I desired for

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

CodePudding user response:

The problem with your code is that identity doesn't have 3 different null lists, it has 3 of the exact same null list. That's why in each iteration, you change value of all of them.

For example, you'll find that instead of the last for loop, if you simply run the following code:

identity[1][1]=1
print(identity)

you'll find that the outcome is

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

If you want to create an identity matrix with list, you can do the following: in each ith iteration, you append a row where the ith element is 1:

identity = []
for i in range(3):
    row = [0]*3
    row[i] = 1
    identity.append(row)

As a function:

def eye(size):
    identity = []
    for i in range(size 1):
        row = [0]*(size 1)
        row[i] = 1
        identity.append(row)
    return identity

eye(3)

Output:

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

CodePudding user response:

You can use Numpy Library to create easily

import numpy as np 
data = np.eye(rows, columns) 
[![# Let's do that: 
data = np.eye(5,5) 
print(data)][1]][1]

Hope you understood! [1]: https://i.stack.imgur.com/wmKpe.png

CodePudding user response:

Expanding on @enke Answer, you can do it in modular form, creating an identity matrix of as many rows as you want.

def eye(num):
    mat = []
    for i in range(num 1):
        row = [0]*(num 1)
        row[i]=1
        mat.append(row)
    return mat

Now you can easily do

eye(5)

Out[2]: 
[[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]]

CodePudding user response:

identity = [[int(j == i) for j in range(n_rows)] for i in range(n_rows)]

CodePudding user response:

a = int(input('enter the Number of matrix you need:: '))

lis = []


for i in range(a):
    new = [0]*a
    new[i] = 1
    lis.append(new)

# Now you can add many identity matrix, Enjoy!
  •  Tags:  
  • Related