2

How can I flatten three separate two dimensional arrays, while maintaining point correlation? For example, I am creating a meshgrid from a dataset containing position information for x and y, and some correlated data array (cartm). After the interpolation, X2 and Y2 have size 300x300 due to the meshgrid; interpval also size 300x300, since each interpval point is correlated with a single coordinate on the (X2,Y2) meshgrid.

How can I flatten each of these 2d matrices, and maintain the 1:1 correlation between values of interpval and their location on the meshgrid? Ultimately, I would like to end up with an Nx3 array, with an X-location column, a Y-location column, and a column with the corresponding interpolation data. Thanks in advance!

import numpy as np
import scipy.interpolate
import matplotlib.pyplot as plt

# Create x,y vectors
cartx = np.array([0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50])
carty = np.array([1, 23, 4, 6, 12, 15, 16, 18, 20, 21, 22])

# Create data vector
cartm = np.array([5.3, 23, 2, 5, 2, 2.5, 13, 9, 7.5, 1.7, 12])

# Prepare meshgrid, interpolate
cartcoord = zip(cartx, carty)
X = np.linspace(cartx.min(), cartx.max(), 300)
Y = np.linspace(carty.min(), carty.max(), 300)
X2, Y2 = np.meshgrid(X, Y)
interp = scipy.interpolate.LinearNDInterpolator(cartcoord, cartm, fill_value=0)
interpval = interp(X2, Y2)

print(X2.shape, Y2.shape, interpval.shape)
AaronJPung
  • 1,105
  • 1
  • 19
  • 35

1 Answers1

2

You can use the ravel() method to flatten X2, Y2 and interpval. To put them into an Nx3 array, you can use numpy.column_stack. So this should do it:

np.column_stack((X2.ravel(), Y2.ravel(), interpval.ravel()))

For example,

In [91]: X2
Out[91]: 
array([[1, 2],
       [3, 4]])

In [92]: Y2
Out[92]: 
array([[11, 12],
       [13, 14]])

In [93]: Z2
Out[93]: 
array([[21, 22],
       [23, 24]])

In [94]: np.column_stack((X2.ravel(), Y2.ravel(), Z2.ravel()))
Out[94]: 
array([[ 1, 11, 21],
       [ 2, 12, 22],
       [ 3, 13, 23],
       [ 4, 14, 24]])
Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214