在 MATLAB 檔案中建立函式


MATLAB 是一種高階程式語言,用於執行工程和科學運算,例如系統設計和分析、矩陣操作、資料解釋、影像處理、應用程式開發等等。

MATLAB 提供了幾種編寫可重用程式碼的方法,這些程式碼可用於執行重複性任務。MATLAB 中的一種此類程式碼是函式。在本教程中,我將解釋如何在 MATLAB 檔案中建立函式。但在那之前,讓我們先了解一些與 MATLAB 函式相關的基本概念。

什麼是 MATLAB 函式?

在 MATLAB 中,函式是一段程式碼、命令或一組指令,它接收使用者的輸入並根據指令產生結果。

它基本上是一個程式碼塊,建立用於多次重用以執行特定任務。在 MATLAB 中建立函式可以使編碼更容易,減少程式碼錯誤和冗餘,並節省多次重寫相同程式碼所需的大量時間。

MATLAB 中的函式型別

在 MATLAB 中,函式分為兩種型別:

  • 內建函式

  • 使用者自定義函式

內建函式是在 MATLAB 軟體庫中已定義的函式。因此,它也稱為庫函式。內建函式的示例包括 log、sqrt、readtable、writetable、disp、imshow 等等。

另一方面,MATLAB 中的使用者自定義函式是由使用者透過編寫 MATLAB 命令來定義的函式。

如何在 MATLAB 中建立函式

MATLAB 提供了一種標準方法來透過編寫一段程式碼來建立函式。下面解釋了在 MATLAB 檔案中建立函式的分步過程

步驟 (1) - 啟動 MATLAB 命令視窗並建立一個新的函式檔案。為此,在“主頁”選項卡下,單擊“新建”,然後選擇“函式”。

步驟 (2) - 定義函式的簽名。這將採用以下標準語法:

function result = MyFun(input1, input2, input3,…)
   % Function body
end

在此程式碼中,將“MyFun”替換為您函式的名稱。指定函式的輸入引數。

步驟 (3) - 在函式體中,編寫執行所需任務的程式碼。例如:

function result = MyFun(input1, input2, input3)
   % Function body
result = input1 * input2 * input3;	 % find product
end

步驟 (4) - 使用與函式名稱相同的名稱儲存函式檔案。例如,在本例中為“MyFun.m”。

現在,我們可以從 MATLAB 命令視窗呼叫此函式來執行其定義的功能。

讓我們現在考慮一些示例來了解如何在 MATLAB 中建立函式。

示例 (1) - 建立一個函式來計算電路中的電功率

步驟 (1) - 建立一個函式檔案並編寫以下程式碼:

% Define the function to calculate power
function electric_power = CalPower(voltage, current)
   % Expression to calculate power
   electric_power = voltage * current;
end

步驟 (2) - 使用名稱“CalPower.m”儲存此函式檔案。

步驟 (3) - 開啟 MATLAB 命令視窗並呼叫函式“CalPower”,如下所示:

% MATLAB code to call the CalPower function
% Specify the values of voltage and current
voltage = 220;		% in volts
current = 6;		% in amperes

% Call the CalPower function
electric_power = CalPower(voltage, current);

% Display the result
fprintf('The electric power is: %.2f Watts', electric_power);

輸出

The electric power is: 1320.00 Watts

讓我們再舉一個建立函式來計算燈泡消耗能量的例子。

示例 (2) - 建立一個函式來計算 MATLAB 中的電費金額

步驟 (1) - 建立一個函式來計算電費金額:

function BillAmt = ElectricityBill(PowerWatt, WorkHours, RatePerUnit)
   % Expression to calculate total energy consumed in kilowatt-hours (units)
   Energy_Consumed = (PowerWatt * WorkHours) / 1000;

   % Calculate the electricity bill amount
   BillAmt = Energy_Consumed * RatePerUnit;
end

步驟 (2) - 使用名稱“ElectricityBill”儲存此函式檔案。

步驟 (3) - 開啟 MATLAB 命令視窗並呼叫函式“ElectricityBill”,如下所示:

% MATLAB code to calculate electricity bill amount
% Provide input parameters
LampPower = 100;		% in Watts
WorkHours = 8;		% lamp is used per day
price = 6;		% Rs. 6 per unit (adjust as per need)

% Calculate the electricity bill amount
bill_amount = ElectricityBill(LampPower, WorkHours, price);

% Display the result
fprintf('The electricity bill amount for the lamp is: %.2f INR per day', bill_amount);

輸出

The electricity bill amount for the lamp is: 4.80 INR per day

結論

在本教程中,我解釋了函式的概念以及在 MATLAB 中建立函式的分步過程。我還包含了一些示例程式來建立函式,以便更好地理解在 MATLAB 中建立函式所涉及的步驟。

總之,MATLAB 提供了一種標準方法來建立函式以執行特定任務。通常建立函式是為了減少程式碼冗餘並建立可重用程式碼塊,以節省開發新程式碼的時間。

更新於:2023年10月10日

90 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.