0

I am trying to use the numerical integration function 'integral'

I created a function of four polynomial functions

[x; x^2; x^3; x^4]

now I want to integrate this vector row by row using the integral function. I tried making a function handle for the function and passed it to the 'integral' function

function f = test(x)
    f = [x,x^2,x^3,x^4];
end

However, I get the following error when calling it command line:

test_var=@test
integral(test_var,0,1)
Error using  ^ 
One argument must be a square matrix and the other must be a scalar. 
Use POWER (.^) for elementwise power.

Error in test (line 2)
    f = [x,x^2,x^3,x^4];

Error in integralCalc/iterateScalarValued (line 314)
            fx = FUN(t);

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);
Irreducible
  • 864
  • 11
  • 24

1 Answers1

0

According to the documentation of integral:

q = integral(fun, xmin, xmax)

  1. For a scalar-valued function fun you need to define the function so that it accepts vector input and produces vector output.

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

  2. If you have a vector-valued function fun you need to use the input flag 'ArrayValued':

    Set this flag to true to indicate that fun is a function that accepts a scalar input and returns a vector, matrix, or N-D array output.

    and in that case the requirement in item 1 above is not necessary:

    If you set the 'ArrayValued' option to true, then fun must accept a scalar and return an array of fixed size.


So, you need to add the input flag 'ArrayValued' to indicate that you have a vector-valued function:

f = @(x) [x; x^2; x^3; x^4]; % or [x; x.^2; x.^3; x.^4];
integral(f, 0, 1, 'ArrayValued', true) % or integral(@f, 0, 1, 'ArrayValued', true)
                                       % if f is defined in a file

gives

ans =
   0.500000000000000
   0.333333333333333
   0.250000000000000
   0.200000000000000
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147