Evaluate integral of vectorial function
Show older comments
Dear all i want to evaluate an integral for a function with different values for some parameters but, instead of performing it in a loop, i would like to do it vectorializing
fun = @(x,c) 1./(x.^3-2*x-c);
q = integral(@(x)fun(x,c),0,c)
where the parameter c is a mx1 vector. and the result q of the integration should be a mx1 vector as well. However, if i define c as a vector the integration does not work. In mycase, performing a the integral into a loop is very time consuming. Is there another way?
1 Comment
John BG
on 28 Dec 2016
are you going to accept an answer among the ones supplied?
would you please be so kind to comment?
Accepted Answer
More Answers (3)
Star Strider
on 25 Dec 2016
The arrayfun function may do what you want.
See if this works for you:
c = 1:5; % Create ‘c’
fun = @(x,c) 1./(x.^3-2*x-c);
q = @(c) integral(@(x)fun(x,c),0,c);
r = arrayfun(q,c)
David Goodmanson
on 26 Dec 2016
Hello Davide, I believe an explicit solution is
cvec = .01:.01:20;
q = [];
for c = cvec
R = roots([1 0 -2 -c]);
r = R(1); s = R(2); t = R(3);
I = real( ((r-s)*(r-t))^-1*log((c-r)/(-r)) ...
+((s-t)*(s-r))^-1*log((c-s)/(-s)) ...
+((t-r)*(t-s))^-1*log((c-t)/(-t)) );
q = [q I]; % should really preallocate instead
end
plot(cvec,q);
There is a pole in q at c = sqrt(3). The values of q to the right of sqrt(3) are probably correct if q is taken to be the principal value of the integral. The code does not work for c exactly at zero.
Walter Roberson
on 27 Dec 2016
Your question is ambiguous. Are you doing the equivalent of
for K = 1 : length(c)
this_c = c(K);
result(K) = integral( @(x) fun(x, this_c), 0, this_c);
end
where you are producing one output for each c value, with the individual value of c used in the calculation and also as the upper bound for the same calculation?
Or are you doing the equivalent of
for K_outer = 1 : length(c)
c_outer = c(K_outer);
for K_inner = 1 : length(c)
c_inner = c(K_inner)
result(K_outer, K_inner) = integral( @(x) fun(x, c_inner), 0, c_outer);
end
end
where you are producing one output for each combination of c values?
MATLAB's integral() function cannot handle either possibility with a single step. It can, however, do
for K_outer = 1 : length(c)
c_outer = c(K_outer);
result(K_outer, :) = integral( @(x) fun(x, c), 0, c_outer, 'ArrayValued', true);
end
This unfortunately cannot be converted to handle the case where each corresponding value is used in the function and as the upper bound.
Categories
Find more on Calculus 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!