I need to generate multiple results but one at a time, as opposed to everything at once in an array.
How do I do that in Matlab with a generator like syntax as in Python?
I need to generate multiple results but one at a time, as opposed to everything at once in an array.
How do I do that in Matlab with a generator like syntax as in Python?
Wolfgang Kuehn
On
In MATLAB (not yet? in Octave), you can use closures (nested, scoped functions):
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
and then
iterator = MyTimeStampedValues([1 2 3 4 5]);
[v, ts, done] = iterator(); % [1, '13-Jan-2014 23:30:45', false]
[v, ts, done] = iterator(); % ...
Copyright © 2021 Jogjafile Inc.
When executing functions that use the
yieldkeyword, 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 toxrangefunction in python:Here is how we use the iterator:
Note the when using the construct
for .. in ..in Python on iterators, it internally does a similar thing.You could write something similar using regular functions instead of classes, by using either
persistentvariables or a closure to store the local state of the function, and return "intermediate results" each time it is called.