speed up integrating the same function over many overlapping intervals?
조회 수: 9 (최근 30일)
이전 댓글 표시
I need to compute many different integrals of the same function fn, essentially like this:
Xint = size(X);
for i=1:numel(X)
Xint(i) = integral(fn,0,X(i)); % fn is continuous
end
The problem is that X is large and computation of fn is slow, so this simple loop takes quite a long time. My question is, what is the best way to speed up this loop?
It does seem like considerable speed-up should be possible, because each time through the loop the integral computation evaluates fn at many almost-the-same points from 0 to X(i)--the range of the X(i)'s is about 400-2000. But what's the best approach? E.g. maybe just order the X's and compute the integrals in pieces, 0 to min(X), then min(X) to 2nd-smallest-X, etc (but isn't there a danger that the errors of approximation will accumulate)? Or maybe precompute fn at a bunch of X's and use trapz (but how to choose those to-be-precomputed X's to ensure the desired level of accuracy)? Or precompute fn, spline it, and then let integral work with the spline_of_fn?
Given all the work that has been done on numerical methods of integration, it seems like someone must have studied how to do this most effectively, but I can't find anything on it. So, I'd appreciate any pointers or tips.
Thanks,
댓글 수: 4
Paul
2021년 9월 11일
Interesting. Do you have good reason to assume that the latter is more accurate? I wonder if this difference between the two approaches is unique to the function in question.
채택된 답변
Alan Stevens
2021년 9월 10일
How about using cumtrapz to do the cumulative integral from 0 to max(X) just once, then select the sections specified by X(i).
댓글 수: 3
Walter Roberson
2021년 9월 11일
integral() and the older functions such as quadgk() use adaptive step-sizes, with different methods for judging when adaption is needed, using different weights and number of evaluations, and using different methods for dealing with infinities.
"Black-box" functions are difficult to integrate reliably.
추가 답변 (1개)
Paul
2021년 9월 12일
In your question you said that fn is continuous. If it's sufficiently smooth, ideally with continuous first derivative, you can use an ode solver to get the value of the integral at the points you specify in the tspan vector. For example:
fn = @(x) (sin(x));
odefun = @(t,x) (fn(t));
X = linspace(0,1,10)*2*pi;
[~,intvalues] = ode23(odefun,X,0); % note, X(1) = 0, using ode23 jsut to illustrate
plot(X,intvalues,X,-cos(X)+1,'o'),grid % compare to truth solution
Of course you'll have to consider all the other options for the ode solver.
I have absolutely no idea how accurate or fast this solution is compared to any other solutions discussed in this thread, but at least it will give you the values of the integral at the specified values in X in one go.
댓글 수: 0
참고 항목
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!