1

I have an array that is (219812,2) but I need to split to 2 (219812).

I keep getting the error ValueError: operands could not be broadcast together with shapes (219812,2) (219812)

How can I accomplish?

As you can see, I need to take the two separate solutions from u = odeint and multiple them.

def deriv(u, t):
    return array([ u[1], u[0] - np.sqrt(u[0]) ])

time = np.arange(0.01, 7 * np.pi, 0.0001)
uinit = array([ 1.49907, 0])
u = odeint(deriv, uinit, time)

x = 1 / u * np.cos(time)
y = 1 / u * np.sin(time)

plot(x, y)
plt.show()
dustin
  • 4,309
  • 12
  • 57
  • 79

3 Answers3

3

To extract the ith column of a 2D array, use arr[:, i].

You could also unpack the array (it works row wise, so you need to transpose u so that it has shape (2, n)), using u1, u2 = u.T.

By the way, star imports aren't great (except maybe in the terminal for interactive use), so I added a couple of np. and plt. to your code, which becomes:

def deriv(u, t):
    return np.array([ u[1], u[0] - np.sqrt(u[0]) ])

time = np.arange(0.01, 7 * np.pi, 0.0001)
uinit = np.array([ 1.49907, 0])
u = odeint(deriv, uinit, time)

x = 1 / u[:, 0] * np.cos(time)
y = 1 / u[:, 1] * np.sin(time)

plt.plot(x, y)
plt.show()

It also seems like a logarithmic plot looks nicer.

jorgeca
  • 5,482
  • 3
  • 24
  • 36
  • 1
    @dustin Make sure you're not computing/plotting something else. This shows how to "split" an array, which I think answers your question. We won't be able to help you solve your other question without more information. – jorgeca Apr 11 '13 at 17:15
  • 1
    @dustin Do you want `plt.plot(time, u[:,0])`? – jorgeca Apr 11 '13 at 17:31
  • @dustin There are possibly a few other problems with your script, and if you are interested in getting it to work, you should ask another question about the actual problem you're interested in solving. One thing I notice is that your `deriv` equation accepts a `t` argument and never uses it. Also it is splitting the arrays by row, not by column. – askewchan Apr 11 '13 at 18:08
  • @askewchan [numerically solving odes](http://stackoverflow.com/questions/15928750/numerical-ode-solving-in-python) Here is a link to another method of solving it but still no luck. – dustin Apr 11 '13 at 20:48
1

It sounds like you want to index into the tuple:

foo = (123, 456)
bar = foo[0] # sets bar to 123
baz = foo[1] # sets baz to 456

So in your case, it sounds like what you want to do might be...

u = odeint(deriv, uinit, time)

x = 1 / u[0] * np.cos(time)
y = 1 / u[1] * np.sin(time)
Amber
  • 507,862
  • 82
  • 626
  • 550
  • that returned the same error I am getting: `ValueError: operands could not be broadcast together with shapes (2) (219812)` – dustin Apr 11 '13 at 15:58
  • 1
    It would be useful to mention that error in your original post. – Amber Apr 11 '13 at 16:01
1
u1,u2 = odeint(deriv, uinit, time)

maybe ?

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179