Given an NxM matrix in NumPY, I wish to down-sample this to an NxO matrix (O <<< M) such that the values in the NxO matrix are linearly interpolated from equally spaced samples in the original matrix.
As an example, consider a 3x10 matrix:
[
[1 2 3 4 5 6 7 8 9 10]
[10 9 8 7 6 5 4 3 2 1 ]
[4 6 4 6 4 6 4 6 4 6 ]
]
If I were to down-sample this to a 3x4 matrix, the values might align like so:
1 2 3 4 5 6 7 8 9 10
|---|---|---|---|---|---|---|---|---|
* * * *
1 2 3 4
In general given M original elements being down-sampled to O new elements, the first element should be sampled from (M-1)/(O+1)
with additional samples being taken at steps of (M-1)/(O+1)
. This can be seen in the image above, where 10 original elements yields 9 "gaps" between the elements. We wish to divide this distance of 9 "gaps" into 5 equals parts (leaving equal space on the left and right with equal spacing between each of the elements). So each new element is 9/5 = 1.8 "gaps" apart:
- New element 0 = Old element 1.8
- New element 1 = Old element 3.6
- New element 2 = Old element 5.4
- New element 3 = Old element 7.2
Using basic linear interpolation, we can say that "element 1.8" is 80% of element 2 plus 20% of element 1
Therefore my final matrix would look like so:
[
[2.8 4.6 6.4 8.2]
[8.2 6.4 4.6 2.8]
[4.4 4.8 5.2 5.6]
]
I considered just writing a function to compute the output values and using np.apply_along_axis()
method, but then I saw this StackOverflow post saying that doing so is just a flimsy wrapper around a for-loop and you're better off vectorizing your function.
So how would one vectorize this? Can it be done?