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 let me explain the algorithm.
input_array = numpy.array([1, 2, 3, 4])
I want to 'expand' or 'extend' each element in this array to 4 points. So, element zero (value 1) would be expanded to these 4 points:
[0, 1, 1, 0]
This would happen for each element to end up with a final array of:
[0, 1, 1, 0, 0, 2, 2, 0, 0, 3, 3, 0, 0, 4, 4, 0]
I'd like to make the code slightly generic so that I could also perform this 'expansion' in a different way. For example:
input_array = numpy.array([1, 2, 3, 4])
This time each point is expanded by adding += .2 to each point. So, the final array would be:
[.8, .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]
The code I'm currently using looks like this. It's a pretty naive approach that works but seems like there would be a way to speed it up for large arrays:
output = []
for x in input_array:
output.append(expandPoint(x))
output = numpy.concatenate(output)
def expandPoint(x):
return numpy.array([0, x, x, 0])
def expandPointAlternativeStyle(x):
return numpy.array([x - .2, x - .2, x + .2, x + .2])