Reputation: 17
I have a pretty simple question-
I'm looking for a way to interpolate a bunch of 3x3 matrices that I have stored in a 3D numpy array. Basically I need to repopulate a numpy array with intermediary matrix values calculated linearly just based on each element in their row/column.
Something that turns
[[1 1 1], [1 1 1], [1 1 1]]
(thats a 2x3x3 np.array)
[[5 5 5], [5 5 5], [5 5 5]]
into
[[1 1 1], [1 1 1], [1 1 1]]
[[3 3 3], [3 3 3], [3 3 3]]
(thats a 3x3x3 np.array)
[[5 5 5], [5 5 5], [5 5 5]]
but there needs to be about a hundred matrices between each matrix, then stored back into my Nx [3x3] numpy array.
Upvotes: 1
Views: 4217
Reputation: 114966
You can use scipy.interpolate.interp1d
.
In the following example, a
is an array with shape (4, 3, 3). The interpolated result, b
, has shape (13, 3, 3).
import numpy as np
from scipy.interpolate import interp1d
a = np.empty((4, 3, 3))
a[0, :, :] = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
a[1, :, :] = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
a[2, :, :] = [[1, 1, 1], [1, 2, 3], [10, 20, 30]]
a[3, :, :] = [[5, 5, 5], [3, 4, 5], [20, 40, 60]]
# Create an x-coordinate for each 3x3 array in `a`.
x = np.arange(a.shape[0])
# Create a linear interpolator.
f = interp1d(x, a, axis=0)
# Insert `m` arrays between each 3x3 array in `a`.
m = 3
xx = np.linspace(x[0], x[-1], (a.shape[0] - 1)*(m + 1) + 1)
b = f(xx)
Here are some of the values after running the script in an ipython session:
In [93]: a
Out[93]:
array([[[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]],
[[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]],
[[ 1., 1., 1.],
[ 1., 2., 3.],
[ 10., 20., 30.]],
[[ 5., 5., 5.],
[ 3., 4., 5.],
[ 20., 40., 60.]]])
In [94]: x
Out[94]: array([0, 1, 2, 3])
In [95]: xx
Out[95]:
array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ,
2.25, 2.5 , 2.75, 3. ])
In [96]: b[:5]
Out[96]:
array([[[ 0. , 0. , 0. ],
[ 0. , 0. , 0. ],
[ 0. , 0. , 0. ]],
[[ 0.25, 0.25, 0.25],
[ 0.25, 0.25, 0.25],
[ 0.25, 0.25, 0.25]],
[[ 0.5 , 0.5 , 0.5 ],
[ 0.5 , 0.5 , 0.5 ],
[ 0.5 , 0.5 , 0.5 ]],
[[ 0.75, 0.75, 0.75],
[ 0.75, 0.75, 0.75],
[ 0.75, 0.75, 0.75]],
[[ 1. , 1. , 1. ],
[ 1. , 1. , 1. ],
[ 1. , 1. , 1. ]]])
In [97]: b[-5:]
Out[97]:
array([[[ 1. , 1. , 1. ],
[ 1. , 2. , 3. ],
[ 10. , 20. , 30. ]],
[[ 2. , 2. , 2. ],
[ 1.5, 2.5, 3.5],
[ 12.5, 25. , 37.5]],
[[ 3. , 3. , 3. ],
[ 2. , 3. , 4. ],
[ 15. , 30. , 45. ]],
[[ 4. , 4. , 4. ],
[ 2.5, 3.5, 4.5],
[ 17.5, 35. , 52.5]],
[[ 5. , 5. , 5. ],
[ 3. , 4. , 5. ],
[ 20. , 40. , 60. ]]])
Upvotes: 2