TransWikia.com

Export data from NDSolve when they meet a certain condition

Mathematica Asked on March 15, 2021

I need to export to a txt file the data from the following system of equations:

x'[t] == px[t],
y'[t] == py[t],
px'[t] == x[t]/(2*Sqrt[x[t]^2 + (1 - y[t])^2]),
py'[t] == -0.2 - (1 - y[t])/Sqrt[x[t]^2 + (1 - y[t])^2]

They can be reduced to two equations of x” and y”, but the number of initial conditions is the same so that’s arbitrary.

I successfully solved the system, for example, this way:

sol = NDSolve[{x''[t] == x[t]/(2*Sqrt[x[t]^2 + (1 - y[t])^2]), 
   y''[t] == -0.2 - (1 - y[t])/Sqrt[x[t]^2 + (1 - y[t])^2], 
   x[0] == x'[0] == Pi/3, y[0] == y'[0] == 0.5}, {x, y}, {t, -10, 
   1000}]

Now, how can I export the data from NDSolve when y[t]==0 AND py[t]>0 ? (in a 2-columm table txt file would be great)

One Answer

Even if there is some kind of mistake (typo) the solution is to use WhenEvent with Sow and Reap:

{sol, {pts}} = 
  Reap@NDSolve[{x''[t] == x[t]/(2*Sqrt[x[t]^2 + (1 - y[t])^2]), 
     y''[t] == -0.2 - (1 - y[t])/Sqrt[x[t]^2 + (1 - y[t])^2], 
     x[0] == x'[0] == Pi/3, y[0] == y'[0] == 0.5, 
     WhenEvent[y[t] == 0 && y'[t] > 0, Sow[{t, x[t]}]]}, {x, y}, {t, -10, 1000}];

which gives

pts
(* {{-0.655304, 0.444787}} *)

ready to export.

Correct answer by mmal on March 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP