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?

1

1 Answer 1

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

np.meshgrid is the function I was unable to find. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.