3
$\begingroup$

Suppose I solve the following differential equation numerically:

s = Flatten@
  NDSolve[{Y'[t] == Y[t], 
    Y[0] == {{0.1, 0.2, 0.3}, {0.1, 0.2, 0.2}, {0.3, 0.4, 0.5}}}, 
   Y, {t, 0, 20}]

This yields a result in terms of InterpolatingFunction[]of dimension {3,3} as Yis a 3 by 3 matrix.

Now, if I wish to plot each component Y[[i,j]] from the solution stored in s then how is it possible?

I tried

Plot[ Evaluate[Y[[1,2]][t]/.s],{t,0,20}]

for component Y[[1,2]] but it didn't work.

Any idea how to extract each component from the solution sand plot?

$\endgroup$
4

2 Answers 2

3
$\begingroup$

Indexed was added to Mathematica to replace Part for this sort of problem:

s = Flatten@
  NDSolve[{Y'[t] == Y[t], 
    Y[0] == {{0.1, 0.2, 0.3}, {0.1, 0.2, 0.2}, {0.3, 0.4, 0.5}}}, 
   Y, {t, 0, 20}]

Plot[Evaluate[Indexed[Y[t], {1, 2}] /. s], {t, 0, 20}]

Update: From @andre314

dimensions = Dimensions[Y[0] /. s];
Plot[Evaluate[Flatten@
  Array[Legended[Indexed[Y[t], {##}], {##}] &, dimensions] /. s],
 {t, 0, 20}]
$\endgroup$
4
  • $\begingroup$ While Indexed[] appears here and there on the site, I couldn't find a Q&A that asked and answer the OP's question. Maybe they used to be closed for being in the docs? $\endgroup$
    – Michael E2
    May 3, 2022 at 18:37
  • $\begingroup$ Interestingly, Indexed permits to plot all the curves with differents colors and a legend. Example : dimensions = Dimensions[Y[0] /. s]; Plot[Evaluate[ Array[Legended[Indexed[Y[t], {#1, #2}], {#1, #2}] &, dimensions] /. s], {t, 0, 20}] $\endgroup$
    – andre314
    May 3, 2022 at 19:00
  • $\begingroup$ If you wish, don't hesitate to copy-paste my code and the resulting graphic (no copyright !) $\endgroup$
    – andre314
    May 3, 2022 at 19:07
  • $\begingroup$ @andre314 Thanks! (I added a Flatten so they each get different colors.) $\endgroup$
    – Michael E2
    May 3, 2022 at 20:06
2
$\begingroup$
sValue = Flatten@
  NDSolveValue[{Y'[t] == Y[t], 
    Y[0] == {{0.1, 0.2, 0.3}, {0.1, 0.2, 0.2}, {0.3, 0.4, 0.5}}}, 
   Y, {t, 0, 20}]

Plot[Evaluate[sValue[t]], {t, 0, 20}]  

enter image description here

NDSolveValue does exactly the same calculus than NDSolve
Evaluate is probably useless here.

$\endgroup$
3
  • $\begingroup$ Thanks a lot. Is it possible to plot one component instead of all components at a time? $\endgroup$
    – Epsilon
    May 3, 2022 at 18:26
  • 1
    $\begingroup$ Yes : Plot[Evaluate[sValue[t]][[1, 1]], {t, 0, 20}] $\endgroup$
    – andre314
    May 3, 2022 at 18:29
  • $\begingroup$ Thanks a lot!!! $\endgroup$
    – Epsilon
    May 3, 2022 at 18:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.