Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to construct identity matrix? [duplicate]

Write a function identity(n) that returns the n identity matrix.
For example: identity(3) outputs [[1,0,0][0,1,0][0,0,1]]
I have tried as follow:

def identity(n):
matrix=[[0]*n]*n
i=0
while i<n:
    matrix[i][i]=1
    i+=1
return matrix

Also I tried with range but it did'n work like this

def identity(n):
    matrix=[[0]*n]*n
    k=matrix[:]
    i=0
    for i in range(1,n):
        matrix[i][i]=1
        i+=1
    return k
print(identity(5))

But it output for n = 5:

[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
like image 846
arberavdullahu Avatar asked Mar 24 '26 15:03

arberavdullahu


2 Answers

If numpy is not allowed ... Know this How to define two-dimensional array in python

and do this

def identity(n):
    m=[[0 for x in range(n)] for y in range(n)]
    for i in range(0,n):
        m[i][i] = 1
    return m
like image 161
J Reid Avatar answered Mar 26 '26 04:03

J Reid


This is because the way you are initializing matrix. Each sublist of [[0]*n]*n is the same list [0]*n, or in other words, each row of your matrix is a reference to the same underlying row. You can verify this using id:

> x = [[0]*3]*3
> x
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
> id(x[0])
140017690403112
> id(x[1])
140017690403112
> id(x[2])
140017690403112

TTherefore, when you assign a value to the ith row of your matrix, you're assigning it to all rows. So avoid nested list creation using [0]*n. Instead, use

matrix = [[0]*n for _ in range(n)]

Even simpler, avoid all of this with:

import numpy as np
np.eye(n)
like image 26
wflynny Avatar answered Mar 26 '26 05:03

wflynny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!