3

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?

Epsilon
  • 1,122
  • 4
  • 8
  • Have you seen Indexed[Y[t], {i, j}]? See also https://mathematica.stackexchange.com/questions/144480/how-to-access-the-components-of-a-vector-valued-interpolating-function and https://mathematica.stackexchange.com/questions/126342/nintegrate-of-a-vector-valued-interpolatingfunction-gives-not-numerical/126361#126361 – Michael E2 May 03 '22 at 18:31
  • No, thank you for the links. I will go through it. – Epsilon May 03 '22 at 18:32
  • Yes, that works as well. I have tried this: Plot[Evaluate[Indexed[Y[t], {1, 3}] /. s], {t, 0, 20}] – Epsilon May 03 '22 at 18:37
  • 1
    Bingo! Just what I tried. :) – Michael E2 May 03 '22 at 18:38

2 Answers2

3

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}]
Michael E2
  • 235,386
  • 17
  • 334
  • 747
  • 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? – Michael E2 May 03 '22 at 18:37
  • 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}] – andre314 May 03 '22 at 19:00
  • If you wish, don't hesitate to copy-paste my code and the resulting graphic (no copyright !) – andre314 May 03 '22 at 19:07
  • @andre314 Thanks! (I added a Flatten so they each get different colors.) – Michael E2 May 03 '22 at 20:06
2
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.

andre314
  • 18,474
  • 1
  • 36
  • 69