1
$\begingroup$

I have a coupled first order system of differential equations which I'm solving numerically (my actual system is more complicated so I use this simple example). I'm trying to plot the solutions for different values of $n$ on one graph:

sol = Table[{n, 
   NDSolve[{y'[x] + n z[x] == 0, z'[x] - n y[x] == 0, y[0] == 1, 
     z[0] == 1}, {y, z}, {x, 0, 1}]}, {n, 1, 2}]
Plot[Evaluate[y[x] /. sol[[1]][[2]]], {x, 0, 1}, PlotRange -> All]
Plot[Evaluate[y[x] /. sol[[2]][[2]]], {x, 0, 1}, PlotRange -> All]
Plot[Table[Evaluate[y[x] /. sol[[n]][[2]]], {n, 1, 2}], {x, 0, 1}, 
 PlotRange -> All]

The last line doing this gives me an error "Part::pkspec1: The expression n cannot be used as a part specification." However I can still plot solutions for different $n$s on different graphs, as illustrated by running the previous two lines. What is going wrong and how do I fix it?

Thanks in advance for any help.

$\endgroup$
1
  • $\begingroup$ Have a look at Dimensions[sol[[1]][[2]]]. You can change the last replacement to y[x] /. sol[[n]][[2]]][[1]]. $\endgroup$
    – Natas
    Commented Oct 22, 2020 at 7:31

2 Answers 2

2
$\begingroup$

In my opinion ParametricNDSolve is the ideal command for such situation.

sol = ParametricNDSolve[{y'[x] + n z[x] == 0, z'[x] - n y[x] == 0, 
       y[0] == 1, z[0] == 1}, {y, z}, {x, 0, 1}, {n}]

Plot[Evaluate[Table[y[n][x] /. sol, {n, 1, 2}]], {x, 0, 1}, PlotRange -> All]

enter image description here

$\endgroup$
2
$\begingroup$

Altenative ParametricNDSolveValue

Y = ParametricNDSolveValue[{y'[x] + n z[x] == 0, z'[x] - n y[x] == 0,y[0] == 1, z[0] == 1}, y, {x, 0, 1}, {n}]

Plot[Table[ Y[n][x] , {n, 1, 2}], {x, 0, 1}, Evaluated -> True]

enter image description here

$\endgroup$

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.