Search code examples
functionmatlabhandlenumerical-integration

matlab integral function handle nested


I have a problem with integrating nested function handles in Matlab:

    fun = @(x,y) 2*x*y;
    y = @(x,a) 5*a*x;
    int = integral(@(x)fun(x,y(x,5)),0,2)

The actual nesting goes deeper and the actual functions are more complex but this example pretty much describes my problem which throws 'Error using * Inner matrix dimensions must agree.'


Solution

  • The reason of this problem is that MATLAB tried to pass you a vector expecting that your function would return a vector of values. Try this one (notice the use of point-wise product):

    fun = @(x,y) 2*x.*y;
    y = @(x,a) 5*a.*x;
    int = integral(@(x)fun(x,y(x,5)),0,2)
    

    This this the excerpt from relevant MATLAB 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.