Summing several function values

3 views (last 30 days)
Hello everyone
I'm trying to use 'sum' to sum up several function values like this:
ft = @(x,k) sin(k.*x);
at = @(k) integral(@(x)ft(x,k),0,pi./2);
st = @(n) sum(ft(pi./2,1:n)); % <- This one works
st = @(n) sum(at(1:n)); % <- This one doesn't
The problem is that 'sum' works perfect when original function does not contain 'integral', otherwise, when I try to evaluate, for example, st(2), I get:
Matrix dimensions must agree.
Error in test>@(x,k)sin(k.*x)
Error in test>@(x)ft(x,k)
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);
Error in test>@(k)integral(@(x)ft(x,k),0,pi./2)
Error in test>@(n)sum(at(n))
Can someone help me with this problem?

Accepted Answer

Denis Perotto
Denis Perotto on 25 May 2018
Well, I can't get it, but
integral(@(x)ft(x,k),0,pi./2) ->
integral(@(x)ft(x,k),0,pi./2,'ArrayValued',true)
seems to be a solution =__=

More Answers (1)

Steven Lord
Steven Lord on 25 May 2018
The documentation for the integral function states the following about your integrand function:
"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."
Your problem is a scalar-valued problem. integral is going to call your integrand function [@(x)ft(x,k)] with a vector of values for x.
  • If the vector of values is the same size as k (which in the case of your st function is 1:n) then this will work. Your integrand will return something the same size as both x and k, and the requirements of the integral function will be satisfied.
  • If the vector of values is NOT the same size as k, you will receive an error either because you're trying to multiply vectors of incompatible sizes or because the size of the output will not be the same size as the x input and thus does not satisfy the requirements of the integral function.
  • When you set 'ArrayValued' to true, integral will call your function with a scalar and a scalar times an array returns a result the same size as the array.

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!