1
$\begingroup$

I use NDSolve to obtain solutions of three coupled ODEs. I have 10 solutions, sol1, sol2, ... , sol10, each one has a different boundary condition for one of the functions.

I can plot one of the solutions of one of the functions, A[x], as

Plot[Evaluate[{A[x]}/.sol1], {x, 0, 1}, AxesLabel-> Automatic, PlotLegends -> {A1}]

How can I plot A[x] as obtained in sol1, sol2, ... , sol10, all in one plot? Namely so I can see how A[x] changes as I change this boundary condition.

Thank you!

$\endgroup$
1
  • $\begingroup$ What you need is something like (x^2) /. x -> {3, 4, 5} $\endgroup$
    – Lotus
    Jun 1, 2017 at 14:28

3 Answers 3

1
$\begingroup$

Here is an example of 3 solutions with 3 b.c for y[0]

s1 = NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == 1}, 
   y, {x, 0, 30}];
s2 = NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == 2}, 
   y, {x, 0, 30}];
s3 = NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == 3}, y, {x, 0, 30}];

Here is how you plot them all. You can of course add plot labels too.

Plot[Evaluate[y[x] /. {s1, s2, s3}], {x, 0, 30}, PlotRange -> All]
$\endgroup$
3
$\begingroup$

I would prefer to avoid a loop as suggested by @ChrisK.

soln[y0_?NumericQ] := First@NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == y0}, {y},
 {x, 0, 30}];

Plot[Evaluate[{y[x]} /. soln[#] & /@ Range[1, 4, 1]], {x, 0, 10}, 
 PlotRange -> All, AxesLabel -> {"x", "y"}, 
 PlotStyle -> {Red, Green, Blue, Black}]

enter image description here

You can also try ParametricNDSolve instead of SetDelay.

$\endgroup$
1
$\begingroup$

@Lotus's answer is correct, but it could be tedious to enter the equations for 10 solutions. Here's an automated, extensible version of their solution:

Do[
  s[i] = NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == i}, y, {x, 0, 30}]
, {i, 10}];

Plot[Evaluate[y[x] /. Table[s[i], {i, 10}]], {x, 0, 30}, PlotRange -> All]
$\endgroup$

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.