Home > OS >  Identity Matrix - only integer scalar arrays can be converted to a scalar index
Identity Matrix - only integer scalar arrays can be converted to a scalar index

Time:07-01

I'm doing Identity Matrix, but it comes TypeError: only integer scalar arrays can be converted to a scalar index, and IDK how to fix it, plz help me!

Z = np.array([
[0,2,0,4,4],
[0,0,3,0,0],
[0,0,0,1,0],
[0,2,0,0,0],
[0,0,0,0,0]
])

I = np.eye(Z)
I = np.identity(Z)

Both np.eye and np.identify come to the same error.

CodePudding user response:

The fucntion np.identity() takes an integer argument, not np.array() object as argument. So if you want to create an identity matrix of size nxn you need to calculate the length of Z:

import numpy as np

Z = np.array([
[0,2,0,4,4],
[0,0,3,0,0],
[0,0,0,1,0],
[0,2,0,0,0],
[0,0,0,0,0]
])


I = np.identity(len(Z))
print(I)

Output:

[[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.]]
  • Related