trapint.m

来自「matlab算法集 matlab算法集」· M 代码 · 共 37 行

M
37
字号
function y = trapint (a,b,n,f)
%-----------------------------------------------------------------------
% Usage:       y = trapint (a,b,n,f);
%
% Description: Use the trapezoid rule to numerically integrate the
%              function f(x) over the interval [a,b] using n panels.
%
% Inputs:      a = lower limit of integration
%              b = upper limit of integration
%              n = number of panels (n >= 1)
%              f = string containing name of user-supplied function 
%                  to be integrated. The form of f is:
%
%                  function y = f(x)
%
%                  When f is called it must return the value f(x).
%
% Outputs:     y = estimate of integral
%
% Note:        The truncation error is proportional to n^(-2). 
%-----------------------------------------------------------------------

% Initialize

   n = args (n,1,n,4,'trapint');
   h = (b - a)/n;

% Compute integral

   y = (feval(f,a) + feval(f,b))/2;
   for i = 1 : n-1
      y = y + feval(f,a+i*h);
   end
   y = h*y;
%-----------------------------------------------------------------------

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?