2

I would like to generate a 2-by-N array in python for use with scipy.optimize.curve_fit.

I have a function of two independent variables stored as 1-D arrays, and the data in a 2-D array. curve_fit requires that the data be flattened, which is easy with data.ravel().

However, this is the hack I'm using to generate the 2xN array of ordinate values:

ordinate = np.array([[l,t] for l in length for t in time]).T 

which works, but is slow. What's the (vectorized?) faster way?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Excalabur
  • 304
  • 3
  • 9
  • pv wrote a [numpy cartesian product implementation](http://stackoverflow.com/a/1235363/190597). With that you could use `ordinate = cartesian([length, time])`. – unutbu Jul 15 '15 at 10:15

1 Answers1

4

If I got the question correctly, you are looking to form a 2D mesh out of the two independent variables stored as 1D arrays. So, for the same, you can use np.meshgrid -

time2D,length2D = np.meshgrid(time,length)
ordinate_vectorized = np.row_stack((length2D.ravel(),time2D.ravel()))

Sample run -

In [149]: time
Out[149]: array([7, 2, 1, 9, 6])

In [150]: length
Out[150]: array([3, 5])

In [151]: ordinate = np.array([[l,t] for l in length for t in time]).T

In [152]: ordinate
Out[152]: 
array([[3, 3, 3, 3, 3, 5, 5, 5, 5, 5],
       [7, 2, 1, 9, 6, 7, 2, 1, 9, 6]])

In [153]: time2D,length2D = np.meshgrid(time,length)
     ...: ordinate_vectorized = np.row_stack((length2D.ravel(),time2D.ravel()))
     ...: 

In [154]: ordinate_vectorized
Out[154]: 
array([[3, 3, 3, 3, 3, 5, 5, 5, 5, 5],
       [7, 2, 1, 9, 6, 7, 2, 1, 9, 6]])
Divakar
  • 218,885
  • 19
  • 262
  • 358