在Matlab中的匿名函数中使用for/while循环

编程入门 行业动态 更新时间:2024-10-11 15:17:04
本文介绍了在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 博客的三部分系列文章中对它们进行了详细讨论:第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并具有一些初始值.此外,假设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循环

本文发布于:2023-06-03 23:43:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/485002.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   Matlab

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!