Problem integrating a function handle which contain an integral

10 views (last 30 days)
hello,
i am having problem integrating on two different variables but at different times, the code is this:
C_z=@(z) sqrt(I./(2*pi.*z.*(1-z)));
P_y=@(y) normcdf((quantile-sqrt(rho).*y)./(sqrt(1-rho)));
KL= @(z,p) z.*log(z./p)+(1-z).*log((1-z)./(1-p));
D_y= @(y) integral(@(z) C_z(z).*exp(-I*KL(z,P_y(y))),0,1);
Correct_C_z=@(y,z) C_z(z)./D_y(y);
I have to integrate D_y over y in more complex function:
fun2= @(y,z) normpdf(y).* min(max((z-d),0),u-d)/(u-d).*(Correct_C_z(y,z)).*exp(-I*KL(z,P_y(y)));
Expected_Loss_approx=integral2(fun2,-inf,+inf,0,1);
with parameters
u=0.25;
d=0.17;
quantile=-1.5;
rho=0.4;
but matlab continues giving matrix error. What is giving problem in the integral2 is the D_y as i tried to compute the integral of this function only on y with no results.
Thanks
Piervito

Answers (1)

Steven Lord
Steven Lord on 20 Mar 2019
What requirement does integral2 place on the integrand function you pass into it as the first input? From the documentation: "The function fun must accept two arrays of the same size and return an array of corresponding values. It must perform element-wise operations."
So the y and z passed into your Correct_C_z are arrays, which means the y passed into D_y is also an array. Now what requirement does integral place on the integrand function you pass into it? From its documentation: "For scalar-valued problems, the function y = fun(x) must accept a vector argument, x, and return a vector result, y. This generally means that fun must use array operators instead of matrix operators. For example, use .* (times) rather than * (mtimes). If you set the 'ArrayValued' option to true, then fun must accept a scalar and return an array of fixed size."
So the z with which C_z is called is a vector (since you haven't said your function is ArrayValued) but that vector is likely not the same size as y. Since you need the output of Correct_C_z to be an array, you're going to need to iterate over the elements of y. The easiest ways to do this are probably making D_y a function handle to a normal function rather than an anonymous function (in which case it can contain a for loop) or by using arrayfun in your anonymous function.
D_y= @(y) arrayfun(@(y) integral(@(z) C_z(z).*exp(-I*KL(z,P_y(y))),0,1), y);
When I tried this with I = 1, the integral2 call warned that it was unsuccessful integrating your function. Looking at fun2 using fsurf it looks quite complicated, and I'm unsure if you need to integrate with infinite limits or if your function falls to 0 fast enough that using smaller finite limits would be sufficient -- maybe -10 to 10?
fsurf(fun2, [-10 10 -10 10])

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!