# How to write the values of a function after each iteration to a .dat file?

I have a differential equation which I solve numerically using NDSolve to obtain y[x]for different values of t.
Example:
t=0.00;
s = NDSolve[{y'[x] == x+2t,, y == 1}, y[x], {x, 0, 30}]
I need the first and last value of the function y[x] which I can obtain by:
f[x_]:=Evaluate[y[x]/.s];
f[]
f[]
Now I want the program to run for every t from 0 to 1 at an interval of 0.01
such that for all 101 time steps of t, I get the values of f[] and f[]. Also I need to create a .dat file which stores the value of t, f[], f[] after each iteration.

Can anyone please guide me how to do this? I am new to Mathematica and have difficulties writing loops. Any help would be much appreciated

Please note that the above differential equation is only for demonstration. The actual one cannot be solved analytically.

• You might want to use ParametricNDSolve[] in this case since your ODE has a varying parameter. – J. M.'s discontentment Nov 9 '17 at 14:42
• Could you please explain using an example? – Apurba Roy Nov 9 '17 at 15:14
• What J.M. meant is whether your t should be variable or is it a fixed constant and you're only interested in solving for one specific value. In any case, I'd do something like t = 0.; f = NDSolveValue[{y'[x] == x+2t, y == 1}, y, {x, 0, 30}]; data = Table[{x, f[x]}, {x, 0, 30, .01}]; Export["data.dat", data, "Table"] – LLlAMnYP Nov 9 '17 at 15:19

You are looking for something like this?

data1 = Table[{t, y /. First@NDSolve[{y'[x] == x + 2 t, y == 1}, y, {x, 0, 30}]},
{t, 0, 1, 0.01}];

data2 = Table[{t, y /. First@NDSolve[{y'[x] == x + 2 t, y == 1}, y, {x, 0, 30}]},
{t, 0, 1, 0.01}];

pdata = ListPlot[{data1, data2}, PlotStyle -> {Red, {Green, Dashed}},
Joined -> True, PlotRange -> All, Frame -> True] points = Cases[Normal@pdata, Line[pts_, ___] :> Flatten[pts, Depth[pts] - 3], Infinity];

ifuncts = Interpolation[#, Method -> "Spline", InterpolationOrder -> 2][t] & /@points;

data = Table[Prepend[ifuncts, t], {t, 0, 1, 0.1}];

TableForm[data, TableHeadings -> {None, Prepend[{"y", "y"}, t]}] Export["C:/tcdata/myfile.txt", data, "Table"]

• Funnily enough, since the initial condition is already specified to begin with, y /. First @ NDSolve[{y'[x] == x + 2 t, y == 1}, y, {x, 0, 30}] is a very complicated way to compute 1. :D – J. M.'s discontentment Nov 10 '17 at 4:38
• @J.M. I agree with you. For the first data point, we dont need to do the calculations but the OP wants it so I did it. – zhk Nov 11 '17 at 4:22