2
$\begingroup$

How do I extract values from NDSolveValue at particular point: for example how do I extract the last point?

$\endgroup$

2 Answers 2

3
$\begingroup$

the result of NDSolveValue is an interpolation function. Example.

sol[x_] = 
 NDSolveValue[{  y''[x] + y[x] == 0 , y[0] == 0, y'[0] == 1, 
   WhenEvent[y[x] == 0, "StopIntegration"]}, y[x], {x, 0, 20}]

you can do sol["Methods"] to see a bunch of descriptve data available:

{"Coordinates", "DerivativeOrder", "Domain", "ElementMesh", "Evaluate", "Grid", "InterpolationMethod", "InterpolationOrder", "MethodInformation", "Methods", "OutputDimensions", "Periodicity", "PlottableQ", "Properties", "QuantityUnits", "ValuesOnGrid"}

Grid holds the actual evaluation points, so the last point is:

 end=sol["Grid"][[-1,1]]

3.14159

in this case since we didn't know the domain in advance its useful to set the range for Plot:

 Plot[sol[x], {x, 0, end}]

enter image description here

here is a plot of the actual solution points:

ListPlot[Transpose[{Flatten[sol["Grid"]], sol["ValuesOnGrid"]}]]

enter image description here

$\endgroup$
1
$\begingroup$

If all you want is the last point, there's an even easier method. Using george's example:

NDSolveValue[{y''[x] + y[x] == 0, y[0] == 0, y'[0] == 1}, y[20], {x, 20}]
   0.912945

and you can see that the value at x == 20 is returned at once.

If you're using WhenEvent[] for event detection, you can use the second argument to throw a result at once:

Quiet[Catch[NDSolveValue[{y''[x] + y[x] == 0, y[0] == 0, y'[0] == 1, 
                    WhenEvent[y[x] == 0, Throw[{x, y[x]}]; "StopIntegration"]},
                   {}, {x, ∞}]], NDSolveValue::noout]
   {3.14159, 1.00614*10^-16}

and you get the point where the integration was stopped, without needing to produce the usual InterpolatingFunction[] output.

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