在Matlab中的匿名函数中使用for/while循环 [英] using for/while loops in anonymous functions in Matlab

查看:468
本文介绍了在Matlab中的匿名函数中使用for/while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现匿名函数非常有用,但是很多时候我需要使用循环才能使该函数正常工作.例如:

I have found anonymous function pretty useful, but a lot of times I'll need to use a loop in order to make the function work. For example:

while val<tolerance
     .....
end

我知道我可以将函数保存在单独的文件中,有时我可以对代码进行矢量化处理,然后匿名函数可以工作,但是在某些情况下,很难找到for循环的替代方法.

I am aware that I can save the function in a separate file, and that sometimes I can vectorize the code and then the anonymous function can work, but in some cases it is very hard to find an alternative to a for loop.

Matlab文档没有讨论它,或者说这是不可能的.有任何想法吗?

Matlab documentation doesn't discuss it or say it is impossible. Any ideas?

推荐答案

功能编程 Mathworks文件交换上的构造正是您所需要的.这些功能中的每一个都旨在在匿名功能中使用.在有关 Loren on MATLAB Art 博客的三部分系列文章中对它们进行了详细讨论:第2部分

The Functional Programming constructs on the Mathworks file exchange are precisely what you need. Each of these functions are designed to be used within anonymous functions. They are discussed in detail in a 3 part series on the Loren on the Art of MATLAB Blog: Part 1, Part 2 and Part 3.

尤其是第3部分讨论了将循环实现为函数.为了完整起见,我将从 Functional Programming FEX提交中借用一些代码,以演示如何在m代码中,我们可以在匿名函数中使用while循环.首先,定义一个loop函数:

In particular Part 3 discusses implementing loops as a function. For completeness, I will borrow some of the code from Functional Programming FEX submission to demonstrate how in m-code we can use a while loop within an anonymous function. Firstly, define a loop function:

   function x = loop(x, continueFcn, f)
   % Inputs:
   % x           - Initial state (can be cell array of arguments to f)
   % continueFcn - Continue function, returns true iff the loop should go on
   % f           - Function of the state (x) to run every iteration
       while ~continueFcn(x{:})
           x = f(x{:});
       end
   end

例如,提供val并具有一些初始值.此外,假设StuffDoneEachWhileLoop是一个函数,该函数定义了变量val在每个while循环中应如何更新.然后:

For the example provide val wile have some initial value, val0 say. Further, suppose that StuffDoneEachWhileLoop is a function that defines how the variable val should update in each while loop. Then:

myFunc = @(n) loop(val0, ...                    % Initialize state
                  @(val) val < tolerance, ...   % OP condition
                  @(val) StuffDoneEachWhileLoop(val));    %  

可以对上述想法进行各种扩展.有关更多详细信息,请参见Tucker McClure的 Functional Programming FEX提交.

Various extensions to the above idea are possible. See Tucker McClure's Functional Programming FEX submission for further details.

这篇关于在Matlab中的匿名函数中使用for/while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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