0

Consider the following array h_0 = (1/16)*np.array([1,4,6,4,1]). What is the easiest way to insert N zeros between each values of h_0 (as part of a function)? So that I get for N=2 for example

>>> array([0.0625, 0.    , 0.    , 0.25  , 0.    , 0.    , 0.375 , 0.    ,
       0.    , 0.25  , 0.    , 0.    , 0.0625])

2 Answers 2

2

The simplest is probably slicing:

h_0 = (1/16)*np.array([1,4,6,4,1])
N = 2

out = np.zeros(h_0.size * (N+1) - N , h_0.dtype)
out[::N+1] = h_0
out
# array([0.0625, 0.    , 0.    , 0.25  , 0.    , 0.    , 0.375 , 0.    ,
#        0.    , 0.25  , 0.    , 0.    , 0.0625])
Sign up to request clarification or add additional context in comments.

1 Comment

Nice solution!!
1

Reshape h_0 to 2D, stack it with zeros and then flatten the result:

import numpy as np

h_0 = (1/16)*np.array([1,4,6,4,1])

N = 2
zeros = np.zeros((h_0.shape[0], N))

print(np.hstack((h_0[:,None], zeros)).reshape(-1)[:-N])
# [0.0625 0. 0. 0.25 0. 0. 0.375 0. 0. 0.25 0. 0. 0.0625]

You can play with this here.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.