# How to create a 2D array of weighted+shifted unit impulses?

## Question:

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) # shifted+weighted unit impulses
``````

Is there a way to get directly `k*np.identity()`? perhaps in `scipy` as this type of array is common in DSP.

``````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.

``````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]]
``````
Categories: questions
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.