Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

When solving an ODE with NDSolve, Mathematica returns an interpolation function. I need a discrete sampling of this function however. Naively, I can write this as (example):

slv = f[t]/. NDSolve[f'[t] == -f[t], f[t], {t,0,10}][[1]];
result = Table[{T, slv/.t->T}, {T,0,10,0.1}];

This is very slow for large times and fine sampling, and I have to do this for a large number of functions.

But in principle, Mathematica must already store a discretized representation of the function for the interpolation function. Is there a way to access this? Or do you have suggestions on how to make the code above faster?

Thanks!

share|improve this question
add comment

1 Answer 1

up vote 3 down vote accepted

A general remark to start with - speed is in the eye of the beholder.

Having said that, there are a couple of things not quite right with your code. First of all, NDSolve isn't doing what you think it does - it returns unevaluated because you didn't give an initial condition and you gave the wrong independent variable - you want to solve for f, not for f[t].

NDSolve[{f'[t] == -f[t], f[0] == 1}, f, {t, 0, 10}][[1]]

or something similar is probably closer to your needs.

Then, you can use something like

slv  = f /. NDSolve[{f'[t] == -f[t], f[0] == 1}, f, {t, 0, 10}][[1]];

and the table is created significantly faster (about a factor 275 on my machine)

result = Table[{T, slv[T]}, {T, 0, 10, 0.1}];

As InterpolatingFunction is listable, it is usually even faster to give it the range of numbers directly:

result = Transpose[{Range[0,10,0.1], slv[Range[0,10,0.1]}]

is faster again, though it only shows if you use a much smaller increment.

If your version of MMA knows about NDSolveValue, you can skip the step with the replacement (not that it saves any time, though):

slv = NDSolveValue[{f'[t] == -f[t], f[0] == 1}, f, {t, 0, 10}];
share|improve this answer
    
Nice answer. Clear & concise, +1. –  rasher Mar 30 at 22:25
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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