I\'m trying to find a way to vectorize an operation where I take 1 numpy array and expand each element into 4 new points. I\'m currently doing it with Python loop. First l
For the first example, you can do an outer product of the input and the template and reshape the result:
input_array = np.array([1, 2, 3, 4])
template = np.array([0, 1, 1, 0])
np.multiply.outer(input_array, template)
# array([[0, 1, 1, 0],
# [0, 2, 2, 0],
# [0, 3, 3, 0],
# [0, 4, 4, 0]])
result = np.multiply.outer(input_array, template).ravel()
# array([0, 1, 1, 0, 0, 2, 2, 0, 0, 3, 3, 0, 0, 4, 4, 0])
Similarly for your second example you can use np.add.outer
np.add.outer(input_array, [-0.2, -0.2, 0.2, 0.2]).ravel()
# array([ 0.8, 0.8, 1.2, 1.2, 1.8, 1.8, 2.2, 2.2, 2.8, 2.8, 3.2,
3.2, 3.8, 3.8, 4.2, 4.2])
See: