isscalar matlab,MATLAB学习笔记—多态函数

多态函数(Polymorphic functions)

什么是多态?

是指函数可以根据输入输出的表达式个数和类型作出不同的反应。

举个栗子:zeros(5,6)生成5×6矩阵,zeros(4)生成4×4的矩阵。

MATLAB中许多内置的函数是多态的(sqrt, max, size, plot, etc.)

如何使自己的函数具有多态性?

nargin: 返回实际的输入参数的个数

nargout: 返回实际要求的输出参数个数

下面这个函数multable(n,m)生成n×m的数阵,我们来使其具有多态性

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的数表和其所有元素和

table = multable(5),只会输出5×5数表

健壮性(Robustness)

一个健壮的函数,会对各种可能出现错误的情况进行处理。上面的函数可以进行如下的优化:

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) %参数不为正整数

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的内容

持续变量(Persistent variables)

和全局变量类似,但又有所区别。

function total = accumulate(n)

persitent summa;

if isempty(summa)

summa = n;

else

summa = summa + n;

end

total = summa;

也就是说,再次调用这个函数的时候,summa的值是接着上次的值的。

重置:clear accumulate

©Fing

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值