7

I want to use an array as argument of a function which will be used to solve an ODE function.

def ode(x, t, read_tau, tau_arr):
  q_ib = x[0:4]
  omega = x[4:7]

  dq_ib = 0.5 * np.dot(gen_omega(omega), q_ib) + read_tau(tau_arr)

  return dq_ib

dq_ib = odeint(rhs, x0, t, args=(b_I, read_tau, tau_arr))

And tau_arr is an (1000, 3) array. The only solution I can think of is first make tau_arr as an iterator and in read_tau().

def read_tau(tau_arr):
  return next(tau_arr)

And the return value of read_tau function will be a 1x3 array which will be used to solved ODE.

My question is how to convert a 2-dimensional array into an iterator, and when calling the iterator with next(), it will return an array row by row.

a = np.array([[1,2,3], [4,5,6]])
convert_to_iter(a)
next(a)
[1,2,3]
next[a]
[4,5,6]
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Lion Lai
  • 1,862
  • 2
  • 20
  • 41

1 Answers1

13

Your desired convert_to_iter() is the Python built-in iter() function.

> a = iter(np.array([[1,2,3], [4,5,6]]))
> next(a)
[1,2,3]
> next[a]
[4,5,6]
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • I only know iter() works for list, I should have tried with np array before posting this question. Thank you. – Lion Lai Jan 27 '19 at 22:00
  • It is all good, somebody else may the same question, and now they can find an answer. – Stephen Rauch Jan 27 '19 at 22:01
  • Is this also possible via [`np.nditer`](https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.nditer.html)? Tried to read the docs but it seems overkill. – jpp Jan 27 '19 at 22:33
  • 1
    @jpp, yup, the nditer is great when doing something more complicated because it then is not a Python loop. But in this simple iteration in which the ODE solver is liable to be the bottle neck, I doubt it is of any value here. – Stephen Rauch Jan 28 '19 at 01:12