I'm looking for an efficient way to get a 2D array like this:
array([[ 2., -0., -0., 0., -0., -0., 0., 0., -0., 0.],
[ 0., -1., -0., 0., -0., -0., 0., 0., -0., 0.],
[ 0., -0., -5., 0., -0., -0., 0., 0., -0., 0.],
[ 0., -0., -0., 2., -0., -0., 0., 0., -0., 0.],
[ 0., -0., -0., 0., -5., -0., 0., 0., -0., 0.],
[ 0., -0., -0., 0., -0., -1., 0., 0., -0., 0.],
[ 0., -0., -0., 0., -0., -0., 0., 0., -0., 0.],
[ 0., -0., -0., 0., -0., -0., 0., 2., -0., 0.],
[ 0., -0., -0., 0., -0., -0., 0., 0., -5., 0.],
[ 0., -0., -0., 0., -0., -0., 0., 0., -0., 4.]])
Diagonal elements contains values. My current attempt:
import numpy as np
N = 10
k = np.random.randint(-5, 5, size=N) # weights
xk = k * np.identity(N) # scaled shifted unit impulses
Is there a way to get directly k*np.identity()
? perhaps in scipy
as this type of array is common in DSP.
CodePudding user response:
np.diag([1,2,3]
gives
[[1 0 0]
[0 2 0]
[0 0 3]]
Creates a diagonal matrix for you. In this case you just need to create the diagonal elements accordingly.
So as per your case:
import numpy as np
N = 10
k = np.random.randint(-5, 5, size=N) # weights
xk = np.diag(k)
print(xk)
gives
[[-4 0 0 0 0 0 0 0 0 0]
[ 0 1 0 0 0 0 0 0 0 0]
[ 0 0 1 0 0 0 0 0 0 0]
[ 0 0 0 4 0 0 0 0 0 0]
[ 0 0 0 0 3 0 0 0 0 0]
[ 0 0 0 0 0 -3 0 0 0 0]
[ 0 0 0 0 0 0 4 0 0 0]
[ 0 0 0 0 0 0 0 1 0 0]
[ 0 0 0 0 0 0 0 0 4 0]
[ 0 0 0 0 0 0 0 0 0 -1]]