Summing several function values

2 次查看(过去 30 天)
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?

采纳的回答

Denis Perotto
Denis Perotto 2018-5-25
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 =__=

更多回答(1 个)

Steven Lord
Steven Lord 2018-5-25
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.

类别

Help CenterFile Exchange 中查找有关 Matrix Computations 的更多信息

产品


版本

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by