我制作了一些辅助函数,使用其中的许多函数来运行模拟。
为了使这些辅助函数更加用户友好,我想让用户选择使用更少的参数调用函数(未传递到函数的参数被分配预定义值)。
例如,如果我有一个函数
function [res, val, h, v, u] = compute(arg1, arg2, arg3, arg4)
if nargin < 4 || isempty(arg4) arg4 = 150; end
和像这样定义的函数 runsim
function [res, val, h, v, u] = runsim(v, arg1, arg2, arg3, arg4)
,那么愚蠢的方法是
if nargin < 5 || isempty(arg4)
compute(arg1, arg2, arg3)
else
compute(arg1, arg2, arg3, arg4)
end
另一个解决方案是将参数更改为向量,但不允许我触摸模拟背后的函数。有没有 Matlab 方法来处理这种情况,或者我是否必须用更少的参数一次又一次地编写相同的代码?
I have made some helper functions that run a simulation using a lot of functions inside them.
In order to make these helper functions more user friendly I want to give the user the choice of calling the functions with fewer arguments (the arguments that are not passed into the function are assigned a predefined value).
For example if I have a function
function [res, val, h, v, u] = compute(arg1, arg2, arg3, arg4)
if nargin < 4 || isempty(arg4) arg4 = 150; end
and the function runsim which is defined like this
function [res, val, h, v, u] = runsim(v, arg1, arg2, arg3, arg4)
the silly way to do it is
if nargin < 5 || isempty(arg4)
compute(arg1, arg2, arg3)
else
compute(arg1, arg2, arg3, arg4)
end
Another solution would be to change the arguments to vectors but I am not allowed to touch the functions behind the simulation. Is there a Matlab way to handle this situation or do I have to write the same code again and again with fewer arguments?
发布评论
评论(3)
您可以使用元胞数组打包和解包函数参数:
输出参数也是如此:
由于 varargin 也是元胞数组,因此您只需弹出要执行的函数所在的字段,然后将其余字段传递为函数的参数。
You can pack and unpack function arguments using cell arrays:
The same goes for output arguments:
Since varargin is also a cell array, you can just pop the field the function you want to execute is in, and then pass the rest of the fields as arguments to the function.
我倾向于同意@Chris 的观点,尽管我想引入一些细微的变化。
如果您的意思是无法更改 compute(),那么您可以使用 varargin 和 Name/Value 习惯用法。
(为了运行此代码,您必须从 Matlabcentral< 下载 catstruct() 函数/a>)
以及调用函数:
I tend to agree with @Chris, though I want to introduce a slight variation.
If what you meant is that you can't change compute(), then you can use varargin, and the Name/Value idiom.
(In order to run this code, you must download the catstruct() function from Matlab central)
And the calling function:
通常的方法是使用
varagin
。例如,要定义一个采用一个必需参数和四个可选参数的函数,我们可以执行类似编辑的操作:另一种方法是使用
inputParser
在您的runsim
函数中。The usual way to do this is to use
varagin
. For example, to define a function which takes one required argument and four optional arguments we could do something likeEdit: An alternative way would be to use
inputParser
in yourrunsim
function.