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

查看:44
本文介绍了在 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 the Art of MATLAB 博客的 3 部分系列中详细讨论了它们:第 1 部分第 2 部分第 3 部分.

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 有一些初始值,例如 val0.此外,假设 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 的函数式编程 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天全站免登陆