2
$\begingroup$

I am looking at the value of x[t] at day t = 200 over several years. I tried to do it using a For-loop but it didn't work. This is my loop:

For[i = 0, i <= 365*years, i++, 
  ss = 
    Table[Flatten[{200 + 365*i, Evaluate[x[200 + 365*i] /. s]}], {t, 0, 365*years}]]

So I am solving, copying and pasting values for each data point, which is takes a lot of time when there a lot of points. Any idea on how to do this with a loop?

My code:

Clear[ss];
a = 0.1;
b = 0.01;
k = (10*Cos[t] + 20);
years = 3;

s = 
  NDSolve[{x'[t] == a*x[t]*(1 - (x[t]/k)) - b*x[t], x[0] == 15}, 
    x, {t, 0, 365*years}];

ss = Table[Flatten[{t, Evaluate[x[t] /. s]}], {t, 0, 365*years}];
data = 
  {{200, Evaluate[x[200] /. s]}, {565, Evaluate[x[565] /. s]}, {930, Evaluate[x[930] /. s]}}

Clear[s]
data1 = 
  {{200, 15.07308029753746}, {565, 15.36783034746959}, {930, 15.704159312861188}};
ListPlot[data1, PlotRange -> All, Frame -> True, AxesOrigin -> {0, 0}]
$\endgroup$
  • $\begingroup$ @march Thank you for your suggestion it works. Since I am looking for day 200 each year I used {t, 200, 365*years, 365} $\endgroup$ – N-A Jul 28 '15 at 19:20
5
$\begingroup$

Generally speaking, one tends to get the most out of Mathematica by trying to avoid explicit loops (e.g. For, Do, etc) in favor of functional expressions (e.g. Map, Fold, Nest, ...).

If I understand what you are looking for, all you need is the following:

(* YOUR CODE *)
Clear[x];
a = 0.1;
b = 0.01;
k = (10*Cos[t] + 20);
years = 3;

s = NDSolve[{x'[t] == a*x[t]*(1 - (x[t]/k)) - b*x[t], x[0] == 15}, x, {t, 0, 365*years}];

(* NEW CODE *)
data = {#, x[#] /. First@s} & /@ Range[200, 200 + (years - 1)*365, 365]

ListPlot[data,
 PlotRange -> All, PlotRangePadding -> Scaled[0.05],
 PlotStyle -> PointSize[0.025], AxesLabel -> {"day", None}
]

(* Out: {{200, 15.0731}, {565, 15.3678}, {930, 15.7042}} *)

Mathematica graphics


Alternatively, you could obtain the same results using a Table construct:

data = Table[{t, x[t] /. First@s}, {t, 200, (years - 1)*365, 365}]
$\endgroup$
  • $\begingroup$ Yes this is exactly what I am looking for. Thanks that works. $\endgroup$ – N-A Jul 29 '15 at 2:04

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.