配置MATLAB中函式的執行按鈕


在本文中,我們將學習如何配置MATLAB中函式的執行按鈕。

在MATLAB中,`執行`按鈕用於執行MATLAB程式碼。此外,MATLAB允許我們配置`執行`按鈕以執行特定使用者定義的函式。

配置執行按鈕的演算法

下面解釋了配置MATLAB中執行按鈕以執行特定函式的分步過程

步驟1 - 首先,建立一個新指令碼以開啟MATLAB編輯器。

步驟2 - 定義或建立要為其配置執行按鈕的函式。

例如,我們建立一個名為`MyFun`的函式來執行兩個數字的加法。

function s = MyFun(x, y)
	s = x + y;
end

步驟3 - 現在,從MATLAB編輯器選單中,點選`編輯器`選項卡,然後選擇“執行”,它將顯示可用於執行該函式的命令列表。

步驟4 - 點選列表中的最後一個選項,並將文字“輸入要執行的程式碼”替換為您自己的函式以及輸入引數。

在我們的例子中,我們將輸入以下內容

s = MyFun(x, y)

此程式碼將使用兩個輸入引數`x`和`y`執行函式`MyFun`,並將結果儲存在變數`s`中。

完成後,MATLAB將使用新新增的執行命令替換預設的執行命令。

現在,當我們點選`執行`按鈕時,MATLAB將執行新定義的函式。

完成函式執行按鈕的配置後,嘗試使用相同的函式執行一些MATLAB程式碼。

例如,如果我們執行以下MATLAB程式,我們將根據定義的函式獲得結果。

% MATLAB Program to execute the `MyFun` function
% Specify the value of input arguments
x = 10;
y = 15;
% Call `MyFun` function
s = MyFun(x, y);
disp('The sum of x and y is:');
disp(s);

輸出

The sum of x and y is:
    25

讓我們考慮更多示例來配置特定函式的`執行`按鈕。

示例(1)

% MATLAB code to configure the Run button for a function
function p = ElectPower(v, i)
	p = v * i;
end

為上述函式`ElectPower`配置執行按鈕後,嘗試執行以下MATLAB程式碼。

示例

% MATLAB code to execute the `ElectPower` function
% Specify the values of input arguments
v = 220;
i = 5;
% Call the `ElectPower` function
p = ElectPower (v, i);
disp('The electrical power consumed is:');
disp(p);

輸出

The electrical power consumed is:
        1100

示例(2)

% MATLAB code to configure the Run button for a function
function r = resistance(v, i)
	r = v/i;
end

為上述函式`resistance`配置執行按鈕後,嘗試執行以下MATLAB程式碼。

示例

% MATLAB code to execute the `resistance` function
% Specify the values of input arguments
v = 12;
i = 3;
% Call the `resistance` function
r = resistance(v, i);
disp('The electrical resistance is:');
disp(r);

輸出

The electrical resistance is:
     4

結論

因此,這就是配置MATLAB中函式的執行按鈕的全部內容。MATALB允許我們配置執行按鈕以呼叫特定函式,這使得無需執行整個MATLAB程式中的指令碼即可更容易地測試和除錯各個函式。

更新於: 2023年8月7日

82 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.