是否可以在 MATLAB 中使用递归匿名函数? [英] Is it possible to have a recursive anonymous function in MATLAB?

查看:31
本文介绍了是否可以在 MATLAB 中使用递归匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我反复想应用一个函数,使用过去的输出作为新的输入.为了可读性(我是从数学的角度而不是程序员的角度写的),我想将它定义为一个简单的匿名函数而不是一个完整的函数块.所以,而不是像

I repeatedly want to apply a function, using a past output as the new input. For readability (I'm writing from a mathematics perspective, not a programmer's perspective), I would like to define it as a simple anonymous function instead of a full function block. So, instead of something like

function f=myfun(x,n)
    if n>1
        f=myfun(myfun(x,n-1),1);
    else
        f=expression(x);
    end
end

我希望能够写作

f=@(x,n) ????

有什么办法可以做到吗?

Is there any way this is possible?

推荐答案

在 MATLAB 中拥有递归匿名函数的唯一方法是将函数句柄作为输入传递给自身.然后您可以从匿名函数中调用它.

The only way to have a recursive anonymous function in MATLAB is to pass the function handle to itself as an input. You can then call it from within the anonymous function.

%// 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 函数借自 此处):

This will obviously result in infinite recursion since you don't have any branching logic. If you want to simulate the branching logic, you would need to implement another anonymous function to do this (iif function borrowed from 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 网站上的一系列博客条目,介绍了使用匿名函数进行的此类函数式编程.

There is a really solid series of blog entries on the Mathworks site that goes over this sort of functional programming using anonymous functions.

虽然这是一个有趣的练习,但如果您想让任何人轻松理解您的代码,我绝对不建议您使用它.调试标准函数要清晰得多,也更容易.然后,如果您确实需要匿名函数,请将对该函数的调用包装在匿名函数中.

While this is an interesting exercise, I definitely wouldn't recommend using this if you want anybody to understand your code easily. It is far clearer and easier to debug a standard function. Then if you really need an anonymous function, wrap the call to that function in an anonymous function.

myanonfunc = @(varargin)myfunc(varargin{:});

或者只是为函数创建一个函数句柄

Or just create a function handle to the function

myfunchandle = @myfunc;

这篇关于是否可以在 MATLAB 中使用递归匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆