how to plot trapezoidal rule

67 visualizaciones (últimos 30 días)
alp onur karacay
alp onur karacay el 29 de Dic. de 2021
Respondida: Pratyush Roy el 7 de En. de 2022
Hello i coded trapezoidal rule but how can i plot it ?here is my code
t = 0:0.2:2*pi;
f = @(x) 3*cos(t*1000);
a = 0;
b = 2*pi;
n = length(t)-1;
h =(b-a)/n;
for i=1:1:n-1
sum = sum + f(a+i*h);
end
result = h/2*(f(a)+f(b)+2*sum);
fprintf('%f',result);
  1 comentario
Torsten
Torsten el 29 de Dic. de 2021
Your variable "result" is just a single number, namely the approximated area under the function f in the interval [0:2*pi].
So what do you want to plot ? How the area develops from 0 to 2*pi ?

Iniciar sesión para comentar.

Respuesta aceptada

Pratyush Roy
Pratyush Roy el 7 de En. de 2022
Hi,
One can use the polyshape function to create polygons (trapezium in this case) and use hold on and off to show them in a single figure. The following code might be helpful to understand how this works:
h = 0.2;
t = 0:h:2*pi;
f = @(x) 3*cos(x*1000);
a = 0;
b = 2*pi;
n = length(t);
sum1 = 0;
plot(t,f(t));
hold on;
for i=0:1:n-1
sum1 = sum1 + f(a+i*h);
if (i>=0)
plot(polyshape([a+i*h,a+i*h,a+(i+1)*h,a+(i+1)*h],[0,f(a+i*h),f(a+(i+1)*h),0]),'FaceColor','red');
hold on;
end
end
hold off;
result = h/2*(f(a)+f(b)+2*sum1);
Hope this helps!

Más respuestas (0)

Categorías

Más información sobre Spectral Measurements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by