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?
댓글 수: 0
채택된 답변
추가 답변 (1개)
Steven Lord
2018년 5월 25일
"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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Computations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!