Double Integral of Multiple Functions in Array Form

2 views (last 30 days)

I would like to shorten a numerical integration code by defining a set of functions of x & y that have the individual parts:

(e.g.)
  f0(1)=@(x,y) sin(x)*cos(y)
  f0(2)=@(x,y) sin(x)^2*cos(y)
  ...
  f0(n)=@(x,y) y*sin(x)

and the functions, F(i), to be eventually integrated are obtained by dividing f0(i) by the common denominator:

(e.g.)
cos(x)+y*sin(x)^2

giving:

    F=[f0(1) f0(2) ... f0(n)]/(cos(x)+y*sin(x)^2)

I thought defining F as mentioned above would be sufficient but I get the following error message:

Nonscalar arrays of function handles are not allowed; use cell arrays instead.

How can I overcome this problem?

Accepted Answer

Walter Roberson
Walter Roberson on 1 Oct 2018
You have three choices:
1) use the symbolic toolbox with symbolic expressions. An array of expressions can be divided by an expression. You can then matlabFunction the results into a function handle. If you tell it to store the results in a .m file then it can do common sub expression optimization. In this setup, the array of expressions can be indexed
2) quite similar to the above, but use symbolic functions instead of symbolic expressions. The resulting array cannot be indexed, but can still be used with matlabFunction.
3) use a cell array to hold the function handles to the numeric functions. Construct another function that uses cellfun to invoke each of the function handles and returns a numeric array that you divide by the denominator.
In all three cases, in order to use the function handle that results with integral2, you will need to create a wrapper function that takes vectors of x y coordinates and invokes the function handle on each of them (or similar action), because integral2 does not support 'arrayvalued'.
If the point is to shorten the coding then the more compact approach would probably be to use an array of symbolic expressions and to use nested vpaintegral() calls to express the 2d integration, as vpaintegral can handle arrays of expressions to integrate.
If the point is efficiency of computation then you should reconsider taking into account integral2 lack of support for vector valued functions.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!