"Trapz" function gives result different than what I calculate by hand

6 views (last 30 days)
0
I'm trying to remember how the trapz function works by doing a little manual test on the console:
>> x=linspace(1,5,5)
x =
1 2 3 4 5
>> y=x
y =
1 2 3 4 5
>> trapz(x,y)
ans =
12
However, when I try this example using pen and paper I get this: I=(1+0)x1/2 + (2+1)x1/2 + (3+2)x1/2 + (4+3)x1/2 =0.5 + 1.5 + 2.5 + 3.5 = 8
In the above calculation, I did the sum of the aereas of 4 trapezoids, the first one having the bigger base equal to 1 and the little base equal to 0, the second one having the bigger base equal to 2 and the little base equal to 1, etc.
To test the correctness of my pen-and-paper calculation, I did another example with different arrays:
>> x=linspace(0,5,6)
x =
0 1 2 3 4 5
>> y=x
y =
0 1 2 3 4 5
>> trapz(x,y)
ans =
12.5000
Then I calculated with pen and paper:
I=(1+0)x1/2 + (2+1)x1/2 + (3+2)x1/2 + (4+3)x1/2 + (5+4)x1/2 = 0.5 + 1.5 + 2.5 + 3.5 + 4.5 = 12.5
What am I missing?

Answers (1)

Torsten
Torsten on 2 Aug 2022
For x = y = [1 2 3 4 5],
I = (1+2)/2 + (2+3)/2 + (3+4)/2 + (4+5)/2 = 24/2 = 12.
  1 Comment
Abdallah
Abdallah on 2 Aug 2022
Edited: Abdallah on 2 Aug 2022
Yup, I figured out my mistake: I was calculating the areas of the trapezoids not from y=0 but from y=1, which isn't how integrals work.

Sign in to comment.

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!