Karl
Karl

Reputation: 11

Use of 'ArrayValued' in Matlab numerical integration

Why when performing numerical integration in Matlab with integral does this case need 'ArrayValued' to be set to true:

f = @(x) 5;
integral(f,0,2,'ArrayValued',true)

... while in this case the option isn't needed?:

f = @(x) x;
integral(f,0,2)

Upvotes: 1

Views: 267

Answers (1)

horchler
horchler

Reputation: 18484

From the documentation for integral describing the integrand argument:

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, a constant function like f = @(x) 5 does not return a result the same size as x if x is a vector. The integral function requires this because under the hood it is vectorized for scalar functions for performance – it actually evaluates the integrand at multiple points simultaneously with a single function call.

You can make your constant function compliant and not require 'ArrayValued' to be true with something like this:

f = @(x) 5+0*x;
integral(f,0,2)

Upvotes: 1

Related Questions