多態(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