我的功能的输入数量不确定 [英] uncertain number of inputs for my function

查看:44
本文介绍了我的功能的输入数量不确定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到一个问题,我应该定义一个输入数不确定的函数,也就是说,输入数可能会根据实际情况而有所不同.我应该使用二维阵列还是其他?我不知道struct2cell是否有帮助,以及它是否真正起作用.

I recently came to a problem that I was supposed to define a function with uncertain number of inputs, that is, the number of inputs may vary depending on the practical context. Should I take use of a 2-D array or something else? I don't know if struct2cell helps and how if it really works.

有人有做这件事的最佳方法的想法吗?

Does anyone have an idea of the best way to go about doing this?

我可能还不太清楚,所以请让我知道是否需要澄清.

I've probably not been very clear, so please let me know if anything needs clarifying.

谢谢

推荐答案

有几种解决方法:

如果给定参数与上下文无关,则使用可选输入参数,但是在某些情况下,需要附加输入.

Use optional input arguments if a given parameter means the same regardless of context, but if in some scenarios, additional input is needed.

function out = myFun(first,second,third,fourth)

%# first is always needed
if nargin < 1 || isempty(first)
error('need nonempty first input')
end

%# second is optional
if nargin < 2 || isempty(second)
second = defaultValueForSecondWhichCanBeEmpty;
end

%# etc

您可以将该函数称为out = myFun(1,[],2,3),即为不需要的输入传递一个空数组.

You can call this function as out = myFun(1,[],2,3), i.e. pass an empty array for non-needed inputs.

如果两个输入表示该函数以一种方式使用,而三个输入表示该函数以另一种方式使用(甚至输入表示不同的事物),请使用

If two inputs mean that the function is used one way, and three inputs mean that the function is used in another way (and even the inputs mean different things), use VARARGIN

function out = myFun(varargin)

%# if 2 inputs, it's scenario 1, with 3 it's scenario 2
switch nargin
case 2
   firstParameter = varargin{1};
   secondParameter = varargin{2};
   scenario = 1;
case 3
   firstParameter = varargin{1}; %# etc
otherwise
   error('myFun is only defined for two or three inputs')
end


最后,您还可以将输入作为parameterName/parameterValue对传递.参见例如此问题关于如何处理此类输入的信息.


Finally, you can also have your inputs passed as parameterName/parameterValue pairs. See for example this question on how to handle such input.

这篇关于我的功能的输入数量不确定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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