Trapezoidal numerical integration without use of function?

362 visualizzazioni (ultimi 30 giorni)
I was trying to do trapezoid integration without actually creating a function, but I seem to have done something wrong.
a=0;
b=1;
f=@(x)x.*sin(x);
n=100;
x=linspace(a,b,n+1);
h=(b-a)/n;
qt=sum((h*f((x(1:n)+x(2:n+1)))/2))
This returns 0.4354, when the actual value of the integral is 0.3012. Where am I going wrong with the code?
  2 Commenti
murat onay
murat onay il 21 Mag 2019
Modificato: murat onay il 21 Mag 2019
trapezoid matlab code is here. This code return 0.301180
clc;clear;
a=0;
b=1;
n=100;
h=(b-a)/n;
sum=0;
f=@(x) x.*sin(x);
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);
Mpho
Mpho il 11 Apr 2023
Hi, how would I achieve this if I want to integrate a constant matrix?

Accedi per commentare.

Risposte (3)

John D'Errico
John D'Errico il 3 Nov 2017
Modificato: John D'Errico il 7 Nov 2017
Trapezoidal rule is easy enough. It depends on whether the step is constant or not. The entire point of my response is you need to get the weights correct. If not, then of course your code must fail.
For a constant step size, you need to remember that the weights look like this:
h*[1 2 2 2 2 2 ... 1]/2
So in any interval, we have a trapezoid. The area of a trapezoid is the average of the heights at each end, then multiply by the width.
h*(f(x(i)) + f(x(i+1)))/2
But each trapezoid shares its endpoint with the neighbors. So that gives the first and last points half the weight of the rest. It also gives us a simple way to do trapezoidal rule.
n = 20;
x = linspace(0,pi,n);
dx = x(2) - x(1);
f_x = sin(x);
trapint = (sum(f_x) - (f_x(1) + f_x(end))/2)*dx
trapint =
1.9954
Did we get it correct?
trapz(x,f_x)
ans =
1.9954
Yes. And both agree with the actual result.
syms u
int(sin(u),0,pi)
ans =
2
Could I have done this for unequal spacing? Still easy enough. I'll pick a random spacing here, using a few more points because a random spacing can have some wide places where nothing fell.
n = 50;
x = [0,sort(rand(1,n-2))*pi,pi];
f_x = sin(x);
dx = diff(x);
trapint = dot(dx,(f_x(1:end-1) + f_x(2:end))/2)
trapint =
1.9966
Note that on a function like sin(x) over that interval, trapezoidal rule will tend to underestimate the integral. As you can see, this is exactly what happened, and will always happen for that function, on that interval.

Hiren Rana
Hiren Rana il 11 Nov 2021
a=0; b=1; n=100; h=(b-a)/n; sum=0; f=@(x) x.*sin(x); 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);

VBBV
VBBV il 29 Dic 2021
Modificato: VBBV il 5 Feb 2022
a=0;
b=1;
f=@(x)x.*sin(x);
n=100;
x=linspace(a,b,n+1);
h=(b-a)/n;
qt=sum(h*(f(x(1:n))+f(x(2:n+1)))/2)
qt = 0.3012
You did not use the function correctly. Try above

Community Treasure Hunt

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

Start Hunting!

Translated by