use*_*455 5 python matlab yield generator yield-keyword
我需要一次生成多个结果,而不是一次生成数组中的所有结果.
如何在Matlab中使用像Python一样的语法生成器?
Amr*_*mro 10
当执行使用该yield
关键字的函数时,它们实际上返回一个生成器.生成器是一种迭代器.虽然MATLAB没有提供任何一种语法,但您可以自己实现"迭代器接口".这是一个与xrange
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
Run Code Online (Sandbox Code Playgroud)
以下是我们使用迭代器的方法:
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
Run Code Online (Sandbox Code Playgroud)
注意for .. in ..
在迭代器上使用Python中的构造时,它在内部做了类似的事情.
您可以使用常规函数而不是类来编写类似的东西,使用persistent
变量或闭包来存储函数的本地状态,并在每次调用时返回"中间结果".
在 MATLAB 中(还没有?在 Octave 中),您可以使用闭包(嵌套的作用域函数):
function iterator = MyTimeStampedValues(values)
index = 1;
function [value, timestamp, done] = next()
if index <= length(values)
value = values(index);
timestamp = datestr(now);
done = (index == length(values));
index = index + 1;
else
error('Values exhausted');
end
end
iterator = @next;
end
Run Code Online (Sandbox Code Playgroud)
进而
iterator = MyTimeStampedValues([1 2 3 4 5]);
[v, ts, done] = iterator(); % [1, '13-Jan-2014 23:30:45', false]
[v, ts, done] = iterator(); % ...
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2401 次 |
最近记录: |