Reputation: 1
I have a function f = @(x,y,z) ... I want to perform a finite numerical integral over x with given numerical values for y and z.
At present, I do this as follows -
f2 = @(x) f(x,5,10)
integral(f2,-1,1)
(5 and 10 are really just some y and z that have assumed certain values over the course of the program).
My question is as follows -
Since I have to do this integral over many many values of (y,z) (in a loop typically). Everytime, I have to redefine a function. This presumably makes my program very slow. Is there a more optimal way to go about doing this operation wherein I don't have to constantly redefine my function. I need the program to run faster.
Thanks!
Upvotes: 0
Views: 2676
Reputation: 43
I was able to speed up some looping code (an MCMC) with many integrals using the composite Simpson's method detailed in "Writing Fast Matlab Code" available at the File Exchange:
http://www.mathworks.com/matlabcentral/fileexchange/5685
From the document, here is a one dimensional integration as an example:
h = (b − a)/(N−1);
x = (a:h:b).';
w = ones(1,N); w(2:2:N−1) = 4; w(3:2:N−2) = 2; w = w*h/3;
I = w * f(x);
The document shows 2 and 3d examples as well.
As a downside, the code forgoes some of the adaptive step size in some of the built-in quadrature methods. However, this method is so blazingly fast, I was able to just brute-force integrate to such a high precision that this isn't an issue. (My integrals are all relatively tame, though.)
Hope this helps.
Upvotes: 0
Reputation:
Anonymous functions are slow. How about rewriting f
and f2
as nested functions? For example:
function result = iterate_trough(A, B)
result = 0;
for a = 1:2:A, for b = 5:5:B
result = result + quad(@f2,-1,1);
end; end;
function r = f(x,y,z), r = x+y+z; end
function r2 = f2(x), r2 = f(x,a,b); end
end
Would this diminish the flexibility of your code?
Later edit: Or even better, eliminating the overhead of calling f
:
function result = iterate_trough(A, B)
result = 0;
for a = 1:2:A, for b = 5:5:B
result = result + quad(@f2,-1,1);
end; end;
function r2 = f2(x), r2 = x+a+b; end
end
Upvotes: 1