MATLAB匿名函數
一個匿名的函數就像是在傳統的編程語言,在一個單一的 MATLAB 語句定義一個內聯函數。
它由一個單一的 MATLAB 表達式和任意數量的輸入和輸出參數。
在MATLAB命令行或在一個函數或腳本可以定義一個匿名函數。
這種方式,可以創建簡單的函數,而不必為他們創建一個文件。
建立一個匿名函數表達式的語法如下:
f = @(arglist)expression
在這個例子中,我們將編寫一個匿名函數 power,這將需要兩個數字作為輸入並返回第二個數字到第一個數字次冪。
在MATLAB中建立一個腳本文件,並輸入下述代碼:
power = @(x, n) x.^n; result1 = power(7, 3) result2 = power(49, 0.5) result3 = power(10, -10) result4 = power (4.5, 1.5)
運行如下:
matlab主函數和子函數
舉個例子就明白了,如下:
我們寫一個 quadratic 函數來計算一元二次方程的根。
該函數將需要三個輸入端,二次系數,線性合作高效的和常數項,它會返回根。
函數文件 quadratic.m 將包含的主要 quadratic 函數和子函數 disc 來計算判別。
在MATLAB中建立一個函數文件 quadratic.m 並輸入下述代碼:
function [x1,x2] = quadratic(a,b,c) %this function returns the roots of % a quadratic equation. % It takes 3 input arguments % which are the co-efficients of x2, x and the %constant term % It returns the roots d = disc(a,b,c); x1 = (-b + d) / (2*a); x2 = (-b - d) / (2*a); end % end of quadratic function dis = disc(a,b,c) %function calculates the discriminant dis = sqrt(b^2 - 4*a*c); end % end of sub-function
驗證: