MATLAB – Trapezoidal numerical integration without using trapz
Last Updated :
04 Jul, 2021
Trapezoidal rule is utilized to discover the approximation of a definite integral. The main idea in the Trapezoidal rule is to accept the region under the graph of the given function to be a trapezoid rather than a rectangle shape and calculate its region.
The formula for numerical integration using trapezoidal rule is:
where h = (b-a)/n
Now we take an example for calculating the area under the curve using 10 subintervals.
Example:
Matlab
syms x
a=0;
b=1;
n=10;
f1=1/(1+x^2);
f=inline(f1);
h=(b - a)/n;
X=f(a)+f(b);
R=0;
for i = 1:1:n-1
xi=a+(i*h);
R=R+f(xi);
end
I=(h/2)*(X+2*R);
disp( 'Area under the curve 1/(1+x^2) = ' );
disp(I);
|
Output:
Let’s take another example for calculating the area under the curve using 4 subintervals.
Example:
Matlab
syms x
a=0;
b=1;
n=4;
f1=x^2;
f=inline(f1);
h=(b - a)/n;
X=f(a)+f(b);
R=0;
for i = 1:1:n-1
xi=a+(i*h);
R=R+f(xi);
end
I=(h/2)*(X+2*R);
disp( 'Area under the curve x^2 = ' );
disp(I);
|
Output:
Share your thoughts in the comments
Please Login to comment...