2
$\begingroup$

Quick question! I'm supposed to plot solution curves for the ODE y'(t)+nty(t) = 0, y(0) = 3 with integer n varying from 1 to 6 inclusive. In the process, I have to use interpolated functions obtained via NDSolve, even though the ODE in question does have analytical solutions. The final plot should look like this: enter image description here

I got the graph above using Matlab, which I'm familiar with, but I'm a newbie in the Wolfram language. I began by stating the ODE:

diffEq = y'[t] + n*t*y[t] == 0

Then, I could use DSolve and obtain the analytical solution of the ODE in symbolic form with n as a parameter and proceed to plot the 6 curves, but, as mentioned above, I have to use NDSolve instead. Typing

NDSolve[{diffEq, y[0] == 3}, y[t], {t, 4}]

is no use because NDSolve needs numerical data, and the program cannot generate any without knowing the value of n. I could use a For or Table, but I still don't know how to use these commands appropriately. Some help would be great.

$\endgroup$
1
  • 1
    $\begingroup$ Use ParametricNDSolve $\endgroup$
    – bbgodfrey
    Dec 7, 2021 at 3:31

2 Answers 2

3
$\begingroup$

You might want to consider ParametricNDSolveValue

pNDSolveValue = ParametricNDSolveValue[{y'[t] + n t y[t] == 0, y[0] == 3}, 
  y[t], {t, 4}, {n}]

enter image description here

Plot[Evaluate @ Table[pNDSolveValue[n], {n, 1, 6}], {t, 0, 4}, 
 AxesLabel -> (Style[#, 16] & /@ {t, y[t]}), 
 PlotLegends -> Placed[PromptForm[n, #] & /@ Range[6], Scaled[{.8, .6}]], 
 ImageSize -> Medium]

enter image description here

$\endgroup$
2
$\begingroup$

could use a For or Table, but I still don't know how to use these commands appropriately.

One possibility.

Mathematica graphics

Clear["Global`*"]
ode = y'[t] + n*t*y[t] == 0;
sols = Table[First@NDSolve[{ode, y[0] == 3}, y, {t, 4}], {n, 1, 6}];
leg = Table[Row[{"n = ", n}], {n, 1, 6}];
leg = Placed[LineLegend[leg, 
        LegendFunction -> (Framed[#, FrameMargins -> 0, 
        Background -> White] &)], {Right, Top}];

Plot[Evaluate[y[t] /. sols], {t, 0, 4}, AxesLabel -> {"time", "y(t)"},
 PlotLegends -> leg,
 GridLines -> Automatic, 
 GridLinesStyle -> Directive[Gray, Dashed, Dashing[0.003]],
 BaseStyle -> 12, ImageSize -> 400]

References: The trick to put white background for legend frame thanks to this answer

$\endgroup$

Your Answer

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

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