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?
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 < handleproperties (Access = private)inendmethodsfunction obj = rangeIterator(n)obj.i = 0;obj.n = n;endfunction val = next(obj)if obj.i < obj.nval = obj.i;obj.i = obj.i + 1;elseerror('Iterator:StopIteration', 'Stop iteration')endendfunction reset(obj)obj.i = 0;endend
end
Here is how we use the iterator:
r = rangeIterator(10);
try% keep call next() method until it throws StopIterationwhile truex = r.next();disp(x);end
catch ME% if it is not the "stop iteration" exception, rethrow it as an errorif ~strcmp(ME.identifier,'Iterator:StopIteration')rethrow(ME);end
end
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 persistent
variables or a closure to store the local state of the function, and return "intermediate results" each time it is called.