MATLAB中的梯形數值積分


在數學中,梯形數值積分是一種近似函式在一定區間上定積分的方法。

在梯形數值積分中,曲線被分成多個梯形,然後計算所有梯形的面積並相加以估計曲線下的總面積。這是一種近似函式定積分的基本方法。因此,它不如其他高階積分方法準確。但是,對於簡單的函式,此方法可以提供合理的近似值。

使用MATLAB進行梯形數值積分

在MATLAB中,我們有一個內建函式“trapz”,它允許計算函式的梯形數值積分。此函式計算一組定點資料的近似積分。

但是,此函式可以根據不同的用例具有不同的語法。'trapz'函式常用的語法如下:

  • I = trapz(A);

  • I = trapz(A, B);

  • I = trapz(A, B, dim)

讓我們藉助示例MATLAB程式碼詳細討論這些語法。

(1). 假設資料點之間單位間距的梯形數值積分

語法

我們可以使用'trapz'函式的以下語法來計算向量'A'的數值積分,其中假設向量的資料點之間存在單位間距:

I = trapz(A);

這裡,A是一個向量,其資料點之間具有單位間距。

以下MATLAB程式演示了執行向量梯形數值積分的程式碼實現,假設資料點之間具有單位間距。

Matlab 示例 (1)

% MATLAB code to calculate numerical integration with unit spacing
% Create a sample vector
A = [0, 2, 8, 11, 15, 27];

% Calculate the trapezoidal numerical integral
I = trapz(A);

% Display the integration result
disp('The approximate trapezoidal integration with unit spacing is:');
disp(I);

輸出

The approximate trapezoidal integration with unit spacing is:
   49.5000

解釋

此MATLAB程式使用'trapz'函式計算向量'A'的近似梯形數值積分,其中假設向量'A'的資料點之間具有單位間距。

(2). 指定資料點之間間距的梯形數值積分

語法

'trapz'函式的以下語法用於計算具有指定資料點之間間距的向量的梯形數值積分:

I = trapz(A, B);

此函式將計算向量'B'相對於向量'A'的積分,其中向量'A'指定向量'B'的資料點之間的間距。

請考慮以下MATLAB程式以瞭解此語法的實現。

Matlab 示例 (2)

% MATLAB program to calculate integral of vector with specified spacing between Data points
% Create a sample vector to specify the spacing between data points
A = [2, 4, 6, 7, 8, 9];
% Create a sample vector whose integral to be calculated
B = [0, 2, 8, 11, 15, 27];

% Calculate the trapezoidal integral
I = trapz(A, B);

% Display the result of integration
disp('The approximate trapezoidal integration with specified spacing is:');
disp(I);

輸出

The approximate trapezoidal integration with specified spacing is:
   55.5000

解釋

此MATLAB程式使用'trapz'函式計算向量'B'相對於向量'A'的數值積分。這裡,向量'A'的值指定向量'B'的資料點之間的間距。

(3). 沿指定維度對多維陣列進行梯形數值積分

語法

'trapz'函式的以下語法可用於沿指定維度對多維陣列執行梯形數值積分:

I = trapz(A, dim);

這裡,A是一個多維陣列。

在此函式中,如果'dim = 1',則該函式將沿陣列的列執行積分並返回一個包含積分值的行向量。

如果'dim = 2',則該函式將沿陣列的行執行積分並返回一個包含積分值的列向量。

以下MATLAB程式演示了沿行和列對多維陣列進行數值積分。

Matlab 示例 (3)

% MATLAB program to calculate integral of multidimensional array along specified dimension
% Create a multidimensional array
A = [1 3 5; 4 2 9; 7 5 6];

% Calculate the integral along the columns
I_C = trapz(A, 1);
% Calculate the integral along the rows
I_R = trapz(A, 2);

% Display the results of integration
disp('The approximate integration of A along columns is:');
disp(I_C);
disp('The approximate integration of A along rows is:');
disp(I_R);

輸出

The approximate integration of A along columns is:
    8.0000    6.0000   14.5000

The approximate integration of A along rows is:
    6.0000
    8.5000
   11.5000

解釋

此MATLAB程式使用'trapz'函式計算陣列'A'沿列(維度1)和行(維度2)的積分。

結論

這就是關於在MATLAB中計算梯形數值積分的所有內容。我們可以使用'trapz'函式執行向量或陣列的梯形數值積分。我們在本教程的以上部分解釋了'trapz'函式的不同語法。

更新於: 2023年9月6日

237 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告