在您的情况下,您的每个函数似乎都有不同数量的输入参数。如果是这种情况,matlab 函数nargin 可以检测到,您不必指定额外的method 参数。
例如:
function f = fun(x,y,z)
switch nargin
case 1
f = x.^2; %// run only if ONE argument was specified
case 2
f = fun(x) + y; %// run only if TWO arguments were specified
case 3
f = fun(x,y) ./ z ; %// run only if THREE arguments were specified
otherwise
disp('Houston, we have a problem !!') ; %// run if NO or more than 3 arguments were specified
end
你可以用一个参数调用f,两个或三个都没有问题,Matlab只会执行正确数量的参数对应的函数。
该函数在使用 3 个参数传递时,可以调用自身以计算具有 2 个参数的部分(它可以调用自身以从第一个参数计算部分)。
案例二:如果递归真的不能跳出循环,经典的if ... then就行了:
function f = fun(x,y,z)
if nargin == 3
threeArgs = true ;
twoArgs = true ;
elseif nargin == 2
threeArgs = false ;
twoArgs = true ;
elseif nargin == 1
threeArgs = false ;
twoArgs = false ;
end
for it=1:1e6
f = x.^2; %// If method_number==1 run only this command....
%// ... other computations
if twoArgs
f = f + y ; %// If method_number==2 run also this command.
%// ... other computations
if threeArgs
f = f ./z ; %// If method_number==3 run also this command.
%// ... other computations
end
%// ... other computations only relevant to f(x,y)
end
%// ... other computations only relevant to f(x)
end
这将完全排除递归并确保最少的计算次数。
现在我意识到这看起来有点笨拙的代码,你要求一个没有if ... then 和switch 的解决方案。根据您的计算,有一种方法可以避免任何if 或switch,但可能不适用于所有情况。
想法是将invariant 运算符分配给y 或z,以防它们未被调用。
例子:
function f = fun(x,y,z)
if nargin < 3 ; z = 1 ; end
if nargin < 2 ; y = 0 ; end
for it=1:1e6
f = x.^2;
%// ... other computations just based on X
f = f + y ; %// This always run, but if "y" wasn't specified, it does not modify the result (f+0=f)
%// ... other computations
f = f ./z ; %// This always run, but if "z" wasn't specified, it does not modify the result (f./1=f)
%// ... other computations
end
这避免了代码中的任何流程分支,但我只会在简单的情况下保留此方法,因为无论情况如何,计算总是完成(尽管可能某些 JIT 编译器足够聪明,不会费心去做“无效”)操作)。