1
$\begingroup$

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

$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – DumpsterDoofus Oct 10 '14 at 15:41
  • $\begingroup$ 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 $\endgroup$ – Geo Oct 10 '14 at 17:04
3
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ i dont quite understand how to use properly those functions even afetr reading documentation, but that works. thanks sir! $\endgroup$ – Geo Oct 10 '14 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.