是否可以在 MATLAB 中使用递归匿名函数?
Is it possible to have a recursive anonymous function in MATLAB?
我反复想应用一个函数,使用过去的输出作为新的输入。为了可读性(我是从数学的角度而不是程序员的角度来写的),我想将它定义为一个简单的匿名函数而不是一个完整的函数块。所以,而不是像
function f=myfun(x,n)
if n>1
f=myfun(myfun(x,n-1),1);
else
f=expression(x);
end
end
我希望能够写作
f=@(x,n) ????
有什么办法可以做到吗?
在 MATLAB 中使用递归匿名函数的唯一方法是将函数句柄作为输入传递给自身。然后您可以从匿名函数中调用它。
%// The first input f is going to be an anonymous function
myfun = @(f,x,n) f(f, x, n+1);
%// Then use your anonymous function like this (note the first input)
out = myfun(myfun, x, n);
这显然会导致无限递归,因为您没有任何分支逻辑。如果你想模拟分支逻辑,你需要实现另一个匿名函数来做到这一点(iif
函数借用 here):
%// Anonymous function to simulate if/elseif/else
iif = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();
%// Your anonymous function that is recursive AND has branching
myfun = @(f,x,n)iif(n > 1, ... % if n > 1
@()f(f, f(f, x, n-1), 1), ... % Recurse
true, ... % else
@()expression(x)); % Execute expression()
Mathworks 网站上确实有一个 solid series of blog entries 介绍了这种使用匿名函数的函数式编程。
注意事项
虽然这是一个有趣的练习,但如果您希望任何人都能轻松理解您的代码,我绝对不建议您使用它。调试标准功能更加清晰和容易。然后,如果您确实需要一个匿名函数,请将对该函数的调用包装在一个匿名函数中。
myanonfunc = @(varargin)myfunc(varargin{:});
或者只是为函数创建一个函数句柄
myfunchandle = @myfunc;
我反复想应用一个函数,使用过去的输出作为新的输入。为了可读性(我是从数学的角度而不是程序员的角度来写的),我想将它定义为一个简单的匿名函数而不是一个完整的函数块。所以,而不是像
function f=myfun(x,n)
if n>1
f=myfun(myfun(x,n-1),1);
else
f=expression(x);
end
end
我希望能够写作
f=@(x,n) ????
有什么办法可以做到吗?
在 MATLAB 中使用递归匿名函数的唯一方法是将函数句柄作为输入传递给自身。然后您可以从匿名函数中调用它。
%// The first input f is going to be an anonymous function
myfun = @(f,x,n) f(f, x, n+1);
%// Then use your anonymous function like this (note the first input)
out = myfun(myfun, x, n);
这显然会导致无限递归,因为您没有任何分支逻辑。如果你想模拟分支逻辑,你需要实现另一个匿名函数来做到这一点(iif
函数借用 here):
%// Anonymous function to simulate if/elseif/else
iif = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();
%// Your anonymous function that is recursive AND has branching
myfun = @(f,x,n)iif(n > 1, ... % if n > 1
@()f(f, f(f, x, n-1), 1), ... % Recurse
true, ... % else
@()expression(x)); % Execute expression()
Mathworks 网站上确实有一个 solid series of blog entries 介绍了这种使用匿名函数的函数式编程。
注意事项
虽然这是一个有趣的练习,但如果您希望任何人都能轻松理解您的代码,我绝对不建议您使用它。调试标准功能更加清晰和容易。然后,如果您确实需要一个匿名函数,请将对该函数的调用包装在一个匿名函数中。
myanonfunc = @(varargin)myfunc(varargin{:});
或者只是为函数创建一个函数句柄
myfunchandle = @myfunc;