1
$\begingroup$

So I am solving a differential equation using NDSolve and plotting the results. But I want to extract the data points in the produced plots to a .txt file. I am aware of the method to extract data from a regular plot of a function, but can't seem to figure out for the NDSolve. If this is not the way to do it, what other methods are available?

Module[{m = 1, b = 1, g = 9.8, k = 100, time = 5},
 s = NDSolve[{m g Cos[ϕ[t]] - k (l[t] - b) == 
     m (l''[t] - l[t] ϕ'[t]^2),
    -g Sin[ϕ[t]] == l[t] ϕ''[t] + 2 l'[t] ϕ'[t], 
    l[0] == 1.2, 
    l'[0] == 0, ϕ[0] == 30*π/180, ϕ'[0] == 0},
   {l, ϕ}, {t, 0, time}];
 Print[
  Plot[Evaluate[l[t] /. s], {t, 0, time}, AxesLabel -> {"t", "l"}, 
   ImageSize -> Small]];
 Print[
  Plot[Evaluate[ϕ[t] /. s], {t, 0, time}, 
   AxesLabel -> {"t", "ϕ"}, ImageSize -> Small]];
 (*data = Cases[Plot[Evaluate[l[t]/.s],{t,0,time},Line[data_]:> data, \
-4*)
 Animate[
  Graphics[{Point[{0, 0}], 
     Point[{l[t] Sin[ϕ[t]], -l[t] Cos[ϕ[t]]}],
     Line[{{0, 0}, {l[t] Sin[ϕ[t]], -l[t] Cos[ϕ[t]]}}]} /. s,
   PlotRange -> {{-2 b, 2 b}, {-2 b, 0.1}}], {t, 0, time}]
 ]

enter image description here

$\endgroup$

1 Answer 1

3
$\begingroup$

To get the datapoints of the solution try

sol = Module[{m = 1, b = 1, g = 9.8, k = 100, time = 5}, 
NDSolveValue[{m g Cos[\[Phi][t]] - k (l[t] - b) ==m (l''[t] - l[t] \[Phi]'[t]^2), -g Sin[\[Phi][t]] ==l[t] \[Phi]''[t] + 2 l'[t] \[Phi]'[t], l[0] == 1.2,l'[0] == 0, \[Phi][0] == 30*\[Pi]/180, \[Phi]'[0] == 0}, {l, \[Phi]}, {t, 0, time}]
]

solcontains two interpolation objects. The datapoints of the first solution are

data1=Transpose[{sol[[1]]["Coordinates"][[1]], sol[[1]]["ValuesOnGrid"]}];
Show[Plot[sol[[1]][t], {t, 0, 5}], ListPlot[data1, PlotStyle -> Red]]

enter image description here

$\endgroup$
4
  • 1
    $\begingroup$ Thank you. But for exporting it to a .txt file, would I just add a new line like this: Export["Length.txt", data1, "Table"]? It did not seem to work though. $\endgroup$
    – Dave4152
    Commented Aug 18, 2020 at 12:50
  • $\begingroup$ Yes that's the way! $\endgroup$ Commented Aug 18, 2020 at 12:55
  • $\begingroup$ ok! thank you!! $\endgroup$
    – Dave4152
    Commented Aug 18, 2020 at 12:59
  • $\begingroup$ You're welcome! $\endgroup$ Commented Aug 18, 2020 at 17:57

Your Answer

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

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