how to get a integral vector result very fast with the upper limits which are supplied in an array?
Show older comments
For exmaple,I have a vector x = [1.2, 3.0, 2.5, 4] which is integral upper limit and a function:
tempFunction = @(tVariable)log(1 + 2 * tVariable .^ 3);
Now I want to calculate the definite integral for the function in the intervals:,[0,1.2], [0,3.0] , [0,2.5] , [0,4]。
If I use loops, I know how to do it:
for index = 1 : 4
result(1, index) = quad(tempFunction, 0, x(1, index));
end
Now the problem is x has a dimension of 1 by 14556,using "for" loop is too slow. And I am doing optimization problem. So there is a lot of outer loops in fmincon which called this integral loop. It made my program very very slow.
Is there any method that I can get the integral result fast without using loops? I checked quad and quadv commands, It seems they are all used to handle upper limit is a constant number.
Accepted Answer
More Answers (1)
Teja Muppirala
on 30 Jul 2012
Edited: Teja Muppirala
on 30 Jul 2012
Using ODE45 to do the integration might be faster than using quad, particularly if your x is large:
tempFunction = @(tVariable,y) (log(1 + 2 * (tVariable*x(:)) .^ 3)).*x(:);
[~,result] = ode45(tempFunction ,[0 0.5 1],[0 0 0 0]');
result = result(3,:);
Also, if you can have the tolerance for integration set to be more rough, then it should finish faster as well.
6 Comments
Teja Muppirala
on 30 Jul 2012
That actually worked better than I expected!
tic;
x = rand(1,14556);
tempFunction = @(tVariable,y) (log(1 + 2 * (tVariable*x(:)) .^ 3)).*x(:);
[~,result] = ode45(tempFunction ,[0 0.5 1],zeros(size(x)));
result = result(3,:);
toc;
Andrei Bobrov
on 30 Jul 2012
+1
X
on 30 Jul 2012
Teja Muppirala
on 30 Jul 2012
Edited: Teja Muppirala
on 30 Jul 2012
This is the chain rule. I make a change of coordinates to make the limits of integration 0 to 1, and in doing this, I need to multiply by X.
I = integral of f(t) dt from 0 to X
Let X*u = t, then
I = integral of f(X*u) dt from 0 to X
I = integral of f(X*u)*(dt/du) du from 0 to 1
I = integral of f(X*u)*X du from 0 to 1
X
on 31 Jul 2012
Categories
Find more on MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!