Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

identity matrix in python

#Change the value 3 to the size of the identity matrix
>>>np.identity(3)
array([[1.,  0.,  0.],
       [0.,  1.,  0.],
       [0.,  0.,  1.]])
Comment

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]]
Comment

PREVIOUS NEXT
Code Example
Python :: how to count substring in a string in python 
Python :: statsmodels 
Python :: dataframe print column 
Python :: django login url 
Python :: nested ternary operator python 
Python :: python how to add a string to a list in the middle 
Python :: append a dataframe to an empty dataframe 
Python :: Math Module pow() Function in python 
Python :: django form field class 
Python :: python run bat in new cmd window 
Python :: access to specific column array numpy 
Python :: arrays python 
Python :: split by backslash python 
Python :: check if list is in ascending order python 
Python :: python compare each item of one list 
Python :: hist pandas 
Python :: python tuple get index of element 
Python :: what is the difference between accuracy and loss 
Python :: enumerate in django templte 
Python :: python keyboard hold key 
Python :: tkinter stringvar not working 
Python :: pandas dataframe caption 
Python :: pandas make dataframe from few colums 
Python :: how to sort the order in multiple index pandas 
Python :: Django delete a session value 
Python :: turn False to nan pandas 
Python :: how to generate list in python 
Python :: k fold cross validation from scratch python 
Python :: thousand separator python 
Python :: python move item in list to another list 
ADD CONTENT
Topic
Content
Source link
Name
3+7 =