# Export data from NDSolve when they meet a certain condition

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 solve the system, for example, as this:

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 == x' == Pi/3, y == y' == 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)

• Plotting y[t] shows that y[t]==0 has two solutions on the interval you used. The roots are found using FindRoot[y[t] /. sol, {t, -1}] FindRoot[y[t] /. sol, {t, 4}] which yields {t -> -0.655304} and {t -> 3.66267}, and by inspecting the plot, only {t -> -0.655304} satisfies py[t]>0. So your final data is just a single 2D point, {x[t], y[t]} /. {t -> -0.655304} /. sol // Chop, which yields {0.444787, 0}. I don't quite understand why you need to export this as a TXT file, since it's just a single point, so you could just type it in manually. – DumpsterDoofus Oct 10 '14 at 15:41
• well this is an example only. the equation i really want cross the 0 many times, so it would be better. thanks for the info tho – Geo Oct 10 '14 at 17:04

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 == x' == Pi/3, y == y' == 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}} *)