Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

identity matrix python

# first solution using NumPy and a second one without it

# 1st ****using NumPy****
>>>import numpy as np
>>>np.identity(5) # change value 5 to change matrix size
# output will be an Array
array([[1., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 1.]])

# 2nd ****without using NumPy****

>>>matrix_size = 5 # change value 5 to change matrix size
# use list comprehension
>>>identity_matrix = [
                  [1 if num == index else 0 for index in range(matrix_size)]
                  for num in range(matrix_size)
                  ]
>>>identity_matrix
# output will be a list
[[1, 0, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 1, 0],
 [0, 0, 0, 0, 1]]
Source by numpy.org #
 
PREVIOUS NEXT
Tagged: #identity #matrix #python
ADD COMMENT
Topic
Name
8+7 =