Manipulation of arguments of variadic arguments in 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?

You can pack and unpack function arguments using cell arrays:

a={'foo','bar',42}
fun(a{:}) % is the same as:
fun('foo','bar',42)

The same goes for output arguments:

a,b,c=fun(); % or easier:
c=cell(3,1);
[c{:}]=fun();

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.

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章