Matlab与Python中yield关键字的等效项是什么?

编程入门 行业动态 更新时间:2024-10-21 04:01:59
本文介绍了Matlab与Python中yield关键字的等效项是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要一次生成多个结果,而不是一次生成所有结果.

I need to generate multiple results but one at a time, as opposed to everything at once in an array.

我如何在Matlab中使用像Python这样的语法生成器来做到这一点?

How do I do that in Matlab with a generator like syntax as in Python?

推荐答案

在执行使用yield关键字的函数时,它们实际上返回一个生成器.生成器是迭代器的一种.尽管MATLAB都不提供语法,但是您可以自己实现迭代器接口" .这是类似于python中的xrange函数的示例:

When executing functions that use the yield keyword, they actually return a generator. Generators are a type of iterators. While MATLAB does not provide the syntax for either, you can implement the "iterator interface" yourself. Here is an example similar to xrange function in python:

classdef rangeIterator < handle properties (Access = private) i n end methods function obj = rangeIterator(n) obj.i = 0; obj.n = n; end function val = next(obj) if obj.i < obj.n val = obj.i; obj.i = obj.i + 1; else error('Iterator:StopIteration', 'Stop iteration') end end function reset(obj) obj.i = 0; end end end

这是我们使用迭代器的方式:

Here is how we use the iterator:

r = rangeIterator(10); try % keep call next() method until it throws StopIteration while true x = r.next(); disp(x); end catch ME % if it is not the "stop iteration" exception, rethrow it as an error if ~strcmp(ME.identifier,'Iterator:StopIteration') rethrow(ME); end end

请注意,当在Python中的迭代器上使用构造for .. in ..时,它在内部会执行类似的操作.

Note the when using the construct for .. in .. in Python on iterators, it internally does a similar thing.

通过使用persistent变量或闭包来存储函数的局部状态,您可以使用常规函数而不是类编写类似的内容,并在每次调用时返回中间结果".

You could write something similar using regular functions instead of classes, by using either persistent variables or a closure to store the local state of the function, and return "intermediate results" each time it is called.

更多推荐

Matlab与Python中yield关键字的等效项是什么?

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

发布评论

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

>www.elefans.com

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