MATLAB學(xué)習(xí)筆記—多態(tài)函數(shù)

多態(tài)函數(shù)(Polymorphic functions)

什么是多態(tài)?

是指函數(shù)可以根據(jù)輸入輸出的表達式個數(shù)類型作出不同的反應(yīng)。

舉個栗子:zeros(5,6)生成5×6矩陣,zeros(4)生成4×4的矩陣。

MATLAB中許多內(nèi)置的函數(shù)是多態(tài)的(sqrt, max, size, plot, etc.)

如何使自己的函數(shù)具有多態(tài)性?

nargin: 返回實際的輸入?yún)?shù)的個數(shù)

nargout: 返回實際要求的輸出參數(shù)個數(shù)

下面這個函數(shù)multable(n,m)生成n×m的數(shù)陣,我們來使其具有多態(tài)性

function [table summa] = multable(n,m)
if nargin < 2
    m = n;
end
table = (1:n)' * (1:m);
if nargout == 2
    summa = sum(table(:));
end

[table s] = multable(3,4),會輸出3×4的數(shù)表和其所有元素和

table = multable(5),只會輸出5×5數(shù)表

健壯性(Robustness)

一個健壯的函數(shù),會對各種可能出現(xiàn)錯誤的情況進行處理。上面的函數(shù)可以進行如下的優(yōu)化:

function [table summa] = multable(n,m)

% MULTABLE muliplication table.
% T = MULTABLE(N) return an N-by-N matrix
% containing the multiplication table for
% the integers 1 through N.
% MULTABLE(N,M) returns an N-by-M matrix.
% Both input arguments must be positive integers.
% [T SM] = MULTABEL(...) returns the matrix
% containing the multiplication table in T
% and the sum of all its elements in SM

if nargin < 1    %沒有輸入
    error('must have at least one input argument');
end
if nargin < 2
    m = n;
elseif ~isscalar(m) || m < 1 || m ~= fix(m)  %參數(shù)不為正整數(shù)
    error('m needs to be a positive integer');
end
if ~isscalar(n) || n < 1 || n ~= fix(n)
    error('n needs to be a positive integer');
end

table = (1:n)' * (1:m);
if nargout == 2
    summa = sum(table(:));
end

%后為注釋,在命令行中輸入help multable,可以得到最上面一大段注釋作為help的內(nèi)容

持續(xù)變量(Persistent variables)

和全局變量類似,但又有所區(qū)別。

function total = accumulate(n)
persitent summa;
if isempty(summa)
    summa = n;
else
    summa = summa + n;
end
total = summa;

也就是說,再次調(diào)用這個函數(shù)的時候,summa的值是接著上次的值的。

重置:clear accumulate

?Fing

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容