简体   繁体   中英

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.'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM