# Can't run For loop containg NDSolve and Plot

I easily can solve a delayed differential equation and plot it using the following commands:

c = 1; r = 1;
sol = NDSolve[{x'[t] == -c x[t - r], x[t /; t <= 0] == 1}, x, {t, -1, 5}];
Plot[Evaluate[{x[t]} /. sol], {t, -1, 10}] I would let to solve and plot the results for different r. Using the following code

c = 1; \[Epsilon] = 0.0001;
rset = {0, 0 + \[Epsilon], 1/E, 1/E + \[Epsilon], Pi/2,
Pi/2 + \[Epsilon]};

For[i = 0, i <= Length[rset], i++,
r = rset[[i]];
sol = NDSolve[{x'[t] == -c x[t - r], x[t /; t <= 0] == 1},
x, {t, -1, 5}];
Plot[Evaluate[{x[t]} /. sol], {t, -1, 10}];]


Which produces many errors. How can I solve this problem?

• What is the definition of crset inside Length inside the For loop? Should that be rset? – march Oct 2 '17 at 17:20
• Yes it should be I would correct it now. – AzJ Oct 2 '17 at 17:21

## 2 Answers

Try this instead:

Table[
Plot[
Evaluate@NDSolveValue[{x'[t] == -c x[t - r], x[t /; t <= 0] == 1}, x[t], {t, -1, 5}],
{t, -1, 10}],
{r, rset}
]


Note the use of NDSolveValue, which directly outputs x[t] rather than a replacement rule.

A For loop doesn't output anything, so you would need to use Print. Better to use Table or Do.

As far as why your code didn't work: it's because lists in Mathematica are indexed starting with 1, not zero. You implicitly tried to do

r = rset[]


which evaluates to the Head of the expression rset, which is List and not a number. So NDSolve didn't know what to do.

Why not use ParametricNDSolve/ParametricNDSolveValue? For instance

With[{c=1},
sol=ParametricNDSolveValue[{x'[t]==-c x[t-r],x[t/;t<=0]==1},x,{t,-1,5},r]
]


ParametricFunction[ <> ]

Then, you can plot sol, e.g.:

Plot[Evaluate[sol[Pi/2][t]], {t, -1, 5}] Or, for your rset:

Plot[Evaluate[sol[#][t]], {t, -1, 5}] & /@ rset • Thank you for this answer. I did not know that this function even existed. – AzJ Oct 2 '17 at 19:42