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()

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@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.
@dustin Do you want plt.plot(time, u[:,0])?
@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 numerically solving odes Here is a link to another method of solving it but still no luck.
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)

2 Comments

that returned the same error I am getting: ValueError: operands could not be broadcast together with shapes (2) (219812)
It would be useful to mention that error in your original post.
1
u1,u2 = odeint(deriv, uinit, time)

maybe ?

1 Comment

@dustin Then try u1, u2 = odeint(deriv, uinit, time).T.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.