0
$\begingroup$

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}]

enter image description here

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. enter image description here How can I solve this problem?

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

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[[0]]

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

$\endgroup$
1
$\begingroup$

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}]

enter image description here

Or, for your rset:

Plot[Evaluate[sol[#][t]], {t, -1, 5}] & /@ rset

enter image description here

$\endgroup$
1
  • $\begingroup$ Thank you for this answer. I did not know that this function even existed. $\endgroup$ – AzJ Oct 2 '17 at 19:42

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.