why does 'sum' and 'trapz' function show same result ?

15 views (last 30 days)
Just found the same result for "sum" and "trapz" function. is it same for uniform spacing (i think here is1) in trapz ?
if yes, then can use 'sum' function for integration instead of 'trapz', right ?
if no, what can be the possible reason ?
attached the 'mat' file here.
integration =
summation =

Accepted Answer

John D'Errico
John D'Errico on 14 Dec 2021
Um, no. Sum is not the same as trapz. Are they close, under some circumstances? Well, yes.
format long g
ans =
ans =
Do you see they are not the same result?
Is sum close? Yes. And that is because when you use sum and trapz, trapz first assumes a unit stride between the points. If the stride was not 1, then trapz would not produce something even close. This gets into the question of what an integral is, and what rectangle rule means, etc. I won't teach a beginning calc course here. Sorry. But if we assume a stride of 1, then you still see they are not identical.
Anyway, as you can see, sum is NOT the same. If you look closely at the formula for rectangle rule to approximate an integral, and then look at the formula for trapz, you will see they essentially only differ at the ends. And since your vector B is almost zero at each end, then sum and trapz will be quite close in their prediction.
Walter Roberson
Walter Roberson on 14 Dec 2021
Right, in the case with regular stride and where the endpoints happen to be zero, the trapz and sum happen to have the same result.

Sign in to comment.

More Answers (1)

the cyclist
the cyclist on 14 Dec 2021
sum() and trapz() do not give the same result, even assuming uniform spacing:
Y = [1 2 3 4 5];
ans = 15
ans = 12
It only seemed to be the same in your case, because of the large numbers involved, but sum(B) and trapz(B) do not give the same value in your case, either. Try subtracting those two values, to see the relatively small difference.

Community Treasure Hunt

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

Start Hunting!