Summing up functions using 'sum' leads to wrong values in quadgk
1 view (last 30 days)
Show older comments
Hello, I have a question concerning the following little example:
h = @(x) x.^2 + x.^4;
h2 = @(x) sum( [x.^2, x.^4]);
f = @(x) h(x) .* exp(-abs(x));
f2 = @(x) h2(x) .* exp(-abs(x));
f(3) % same values here
f2(3) %
m = quadgk( f , -inf, inf) % different values here
m2 = quadgk( f2 , -inf, inf) %
The pointwise evaluation of f and f2 yields the same values. Integrating the (pointwise equal) functions f and f2 with quadgk over the real line gives vastly different results. Isn't this strage?! Can some one give me a little hint how this can be? Thanks !
With best regards, Oscar
0 Comments
Accepted Answer
Jan
on 17 May 2014
Edited: Jan
on 17 May 2014
@quadgk calls the function to be integrated with a row vector as input for a faster vectorized processing. Then sum() operates on a longer row vector, because the dimension to operate on was not specified. Relying on the smart automatic detection of the dimension is a source of bugs. Never do this is serious programs.
Solution:
h2 = @(x) sum([x.^2; x.^4], 1); % Semicolon, not a comma!
If you use functions instead of anonymous functions, the debugger can reveal what's going on.
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!