kec*_*ito 3 matlab variadic-functions
我已经制作了一些辅助函数,它们使用其中的许多函数运行模拟.
为了使这些辅助函数更加用户友好,我想让用户选择使用较少的参数调用函数(未传递给函数的参数被赋予预定义的值).
例如,如果我有一个功能
function [res, val, h, v, u] = compute(arg1, arg2, arg3, arg4)
if nargin < 4 || isempty(arg4) arg4 = 150; end
Run Code Online (Sandbox Code Playgroud)
以及像这样定义的函数runsim
function [res, val, h, v, u] = runsim(v, arg1, arg2, arg3, arg4)
Run Code Online (Sandbox Code Playgroud)
这种愚蠢的方式是
if nargin < 5 || isempty(arg4)
compute(arg1, arg2, arg3)
else
compute(arg1, arg2, arg3, arg4)
end
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是将参数更改为向量,但我不允许触及模拟背后的函数.是否有Matlab方法来处理这种情况,或者我必须用较少的参数一次又一次地编写相同的代码?
jpj*_*obs 12
您可以使用单元格数组打包和解压缩函数参数:
a={'foo','bar',42}
fun(a{:}) % is the same as:
fun('foo','bar',42)
Run Code Online (Sandbox Code Playgroud)
输出参数也是如此:
a,b,c=fun(); % or easier:
c=cell(3,1);
[c{:}]=fun();
Run Code Online (Sandbox Code Playgroud)
由于varargin也是一个单元数组,因此您只需弹出要执行的函数所在的字段,然后将其余字段作为参数传递给函数.
| 归档时间: |
|
| 查看次数: |
1708 次 |
| 最近记录: |