我可以对不同类型的参数输入使用相同的函数吗 [英] can I use same functions with the different type of argument inputs

查看:21
本文介绍了我可以对不同类型的参数输入使用相同的函数吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含函数 foo

If I have a MATLAB lab file contains function foo

function [test] = foo(a,b);
test = a+b

如果我想修改那个函数 foo 也会在我的输入中接收添加数据 c在同一个 MATLAB 文件中

If I want to modified that function foo also receive the addition data c in my input in the same MATLAB file

function [test] = foo(a,b,c);
test = a+b+c;

我可以这样做吗?(我尝试了类似的但当我尝试使用它时说我有很多论点.)

Can I do this? (I try the similar but when I try to use it said that I have to many argument.)

推荐答案

varargin 方法在这里很合适,虽然我会稍微不同(见下文).但是,您可以简单地使用 exist<测试第三个参数是否存在/code>(或通过 nargin,但不那么直接且容易出错).

The varargin approach is suitable here, although I would do it slightly differently (see below). However, you can simply test for the existence of the third argument with exist (or via nargin, but that is less direct and error prone).

function test = foo(a,b,c)

if exist('c','var'), % nargin>2
    test = a + b + c;
else
    test = a + b;
end

在代码注释中,也可以对 nargin 进行测试,但是 exist 调用没有那么模糊,如果参数列表是修改(例如订单).

As in the code comment, a test on nargin is also possible, but the exist call is far less ambiguous and will not need a change if the argument list is modified (e.g. order).

注意 varargin 不需要是函数声明中的唯一参数:

Note that varargin does not need to be the only argument in the function declaration:

function test = foo(a,b,varargin)

if nargin>2, % numel(varargin)>0
    test = a + b + varargin{1};
else
    test = a + b;
end

另外,假设您想要任意数量的额外输入(例如 foo(a,b,c,d,...)),您可以使用 varargin 元胞数组.例如,您可以执行 [varargin{:}] 将元素水平连接到一个新数组中.对于垂直串联,您可以执行 vertcat(varargin{:}).我假设 a+b+c 示例只是一个示例,所以我不会在实践中展示这一点,但是您可以以任何您喜欢的方式使用这些数组.

Also, say you want to have any number of extra inputs (e.g. foo(a,b,c,d,...)), you can do to tricks with the varargin cell array. For instance, you can do [varargin{:}] to horizontally concatenate the elements in to an a new array. For vertical concatenation, you can do vertcat(varargin{:}). I'm assuming the a+b+c example was just an example, so I won't show this in practice, but you can use these arrays any way you like.

这篇关于我可以对不同类型的参数输入使用相同的函数吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆