1
$\begingroup$

I have a list whose elements is in the form {{f[x]-> some function of x}}. How do I manipulate it to bring in the form {f1(x), f2(x) ... }. The list is generated by DSolve inside table.

Table[DSolve[{de, y[0] == k}, y[x], x], {k , -2, 2}]

The output is in the form

 {{{y[x] -> -2 E^-x^2}}, {{y[x] -> -E^-x^2}}, {{y[x] ->  0}}, {{y[x] -> E^-x^2}}, {{y[x] -> 2 E^-x^2}}}

I need to plot all these solutions.

I need it in the form

{-2 E^-x^2, -E^-x^2,  0, E^-x^2,2 E^-x^2}

I tried something like

f[x] /. #[[1]] & /@ Table[DSolve[{de, y[0] == k}, y[x], x], {k , -2, 2}]

But no luck :(

$\endgroup$
  • 1
    $\begingroup$ Flatten[yourList][[All,2]] if you need only function bodies $\endgroup$ – k_v Feb 13 '16 at 20:59
6
$\begingroup$

Use Flatten

sol = {{{y[x] -> -2 E^-x^2}}, {{y[x] -> -E^-x^2}}, {{y[x] -> 0}}, {{y[x] -> 
      E^-x^2}}, {{y[x] -> 2 E^-x^2}}};

Plot[Evaluate[y[x] /. sol // Flatten], {x, 0, 1}, 
  PlotLegends -> "Expressions"]

enter image description here

$\endgroup$
4
$\begingroup$

Just a variant: function of parameter and extract solution at start and the use of ParametricNDSolve (though not needed for this particular example but just to show an alternative):

fun[k_] := [x] /. DSolve[{f'[x] == -2 x f[x], f[0] == k}, {f[x]}, x][[1]]
Plot[Evaluate@Table[fun[j], {j, -2, 2}], {x, 0, 1},PlotLegends ->"Expressions"]

or

sol = ParametricNDSolve[{y'[x] == -2 x y[x], y[0] == p}, {y}, {x, 0, 1},{p}];
Plot[Evaluate@Table[y[j][x] /. sol, {j, -2, 2}], {x, 0, 1}]

enter image description here

$\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.