matlabcurve-fittingnumerical-integrationfunction-handle

How do I create function handle from cfit, multiply with other function handle and integrate the term?


I try to get an integral of two function handles in Matlab. The first function handle would be a weibull probability density function and the second function handle is based on a cfit I created with linear interpolation of single points.

x = 0:0.1:35;
fun1 = @(x) wblpdf(x,weibullAlpha,weibullBeta);
fun2 = @(x) feval(cfitObject,x);
fun3 = @(x) (fun(x).*fun2(x));
y = integral(fun3,0,35); % Using quad(fun3,0,35) doesn't work either.

I receive the following error:

Error using integralCalc/finalInputChecks (line 515)
Output of the function must be the same size as the input. If FUN is an array-valued  integrand,
set the 'ArrayValued' option to true.

Error in integralCalc/iterateScalarValued (line 315)
            finalInputChecks(x,fx);

Error in integralCalc/vadapt (line 132)
        [q,errbnd] = iterateScalarValued(u,tinterval,pathlen);

Error in integralCalc (line 75)
    [q,errbnd] = vadapt(@AtoBInvTransform,interval);

Error in integral (line 88)
Q = integralCalc(fun,a,b,opstruct);

Error in test (line 7) % "test" is the name of the script file.
y = integral(fun3,0,35);

The problem must have to do something with "fun2" since the code works just fine with e.g.

fun2 = x.^2;

Note: if I plot fun2 with the cfitObject I don't get an error. It's also possible to integrate the function using quad().

x = 0:0.1:35;
fun2 = @(x) feval(cfitObject,x);
y = quad(fun2,0,35);
plot(x, fun2(x))

Any help is greatly appreciated!


Solution

  • Your code seems to be ok. Probably the problem is that fun2 cannot take vectorized input, it could be resolved by modifying fun2 (cfitObject) to be able to handle vector input or telling the software that the function in the integral is array valued:

    y = integral(fun3, 0, 35, 'ArrayValued', 1);