0

I have a list that I want to build a kernel from [90,50,10]

What I want to do is to get a kernel that looks like -

[[90,0,0]
 [50,0,0]
 [10,0,0]
 [0,90,0]
 [0,50,0]
 [0,10,0]
 [0,0,90]
 [0,0,50]
 [0,0,10]]

I can implement this using a loop, AND I tried doing something in the lines of this -

k = np.array([90,50,10])
for i in k:
    d = np.zeros((3,3))
    np.fill_diagonal(d, i)
    print(d)
[[90.  0.  0.]
 [ 0. 90.  0.]
 [ 0.  0. 90.]]
[[50.  0.  0.]
 [ 0. 50.  0.]
 [ 0.  0. 50.]]
[[10.  0.  0.]
 [ 0. 10.  0.]
 [ 0.  0. 10.]]

The issue is that to reorder the rows, I will need another iteration and np.fill_diagonal is an in-place method so I cant use list comprehensions.

I am looking for a way I can solve this in a vectorized manner without any loops, using only numpy and in a single line of code.

EDIT:

The preferred solution should be able to build a 25X5 kernel if I use a 5X1 array like [90,50,40,30,10]

3 Answers 3

2

you could do:

s = np.array([90,50,10])
size = s.size
o = np.zeros((size ** 2, s.size))
o[np.arange(size**2), np.repeat(np.arange(size), size)] = np.tile(s, size)
print(o)
[[90.  0.  0.]
 [50.  0.  0.]
 [10.  0.  0.]
 [ 0. 90.  0.]
 [ 0. 50.  0.]
 [ 0. 10.  0.]
 [ 0.  0. 90.]
 [ 0.  0. 50.]
 [ 0.  0. 10.]]
Sign up to request clarification or add additional context in comments.

Comments

1

Here's one possible one-liner for, e.g. k = np.array([90, 50, 10]):

np.concatenate([np.pad(k[:, None], ((0, 0), (i, 2-i))) for i in range(k.size)])

Comments

1

IIUC,

#k = np.array([90, 50, 10])
kernel = np.tile(np.identity(k.shape[0])*k, k.shape[0]).reshape(k.shape[0]**2, k.shape[0])
print(kernel)

[[90.  0.  0.]
 [90.  0.  0.]
 [90.  0.  0.]
 [ 0. 50.  0.]
 [ 0. 50.  0.]
 [ 0. 50.  0.]
 [ 0.  0. 10.]
 [ 0.  0. 10.]
 [ 0.  0. 10.]]

2 Comments

Wish we could select 2 answers as top.
Isn't the output here different from the question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.