MATLAB – 不使用 trapz 的梯形数值积分
梯形规则用于发现定积分的近似值。梯形规则的主要思想是接受给定函数图下的区域是梯形而不是矩形并计算其区域。
使用梯形法则进行数值积分的公式为:
其中 h = (ba)/n
现在我们以计算曲线下面积为例使用 10 个子区间。
例子:
Matlab
% MATLAB program for calculate the
% area under the curve ∫_0^11/(1+x^2) dx
% using 10 subintervals specify the variable
% x as symbolic ones The syms function creates
% a variable dynamically and automatically assigns
% to a MATLAB variable with the same name
syms x
% Lower Limit
a=0;
% Upper Limit
b=1;
% Number of segments
n=10;
% Declare the function
f1=1/(1+x^2);
% inline creates a function of
% string containing in f1
f=inline(f1);
% h is the segment size
h=(b - a)/n;
% X stores the summation of first
% and last segment
X=f(a)+f(b);
% variable R stores the summation of
% all the terms from 1 to n-1
R=0;
for i = 1:1:n-1
xi=a+(i*h);
R=R+f(xi);
end
% Formula to calculate numerical integration
% using Trapezoidal Rule
I=(h/2)*(X+2*R);
% Display the output
disp('Area under the curve 1/(1+x^2) = ');
disp(I);
Matlab
% MATLAB program for calculate
% the area under the curve∫_0^1x^2 dx
% using 4 subintervals.
% specify the variable x as symbolic ones
syms x
% Lower Limit
a=0;
% Upper Limit
b=1;
% Number of segments
n=4;
% Declare the function
f1=x^2;
% inline creates a function of
% string containing in f1
f=inline(f1);
% h is the segment size
h=(b - a)/n;
X=f(a)+f(b);
% variable R stores the summation
% of all the terms from 1 to n-1
R=0;
for i = 1:1:n-1
xi=a+(i*h);
R=R+f(xi);
end
% Formula to calculate numerical
% integration using Trapezoidal Rule
I=(h/2)*(X+2*R);
% Display the output
disp('Area under the curve x^2 = ');
disp(I);
输出:
再举一个计算曲线下面积的例子使用 4 个子区间。
例子:
MATLAB
% MATLAB program for calculate
% the area under the curve∫_0^1x^2 dx
% using 4 subintervals.
% specify the variable x as symbolic ones
syms x
% Lower Limit
a=0;
% Upper Limit
b=1;
% Number of segments
n=4;
% Declare the function
f1=x^2;
% inline creates a function of
% string containing in f1
f=inline(f1);
% h is the segment size
h=(b - a)/n;
X=f(a)+f(b);
% variable R stores the summation
% of all the terms from 1 to n-1
R=0;
for i = 1:1:n-1
xi=a+(i*h);
R=R+f(xi);
end
% Formula to calculate numerical
% integration using Trapezoidal Rule
I=(h/2)*(X+2*R);
% Display the output
disp('Area under the curve x^2 = ');
disp(I);
输出: