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

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

回答(1 个)

Torsten
Torsten 2022-8-2
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 个评论
Abdallah
Abdallah 2022-8-2
编辑:Abdallah 2022-8-2
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Numerical Integration and Differentiation 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by