Given a generator:
myVec1 = rand(0:4, 2)
myVec2 = rand(0:4, 8)
myGen = (val1 + val2 for val1 in myVec1, val2 in myVec2)
This is basically a matrix with 2 columns. It can be seen by using collect(myGen).
How can I create a generator which yields two values per call (basically a column)?
Conceptually, something equivalent of:
for myCol in eachcol(collect(myGen))
@show myCol;
end
Just without any explicit allocation of the matrix.
Can I wrap myGen for the following case:
for value1, value2 in myGen
dosomethingelse1(value1, value2)
end
In other words, I am after a way to create a generator which returns 2 (or more?) consecutive values at once and can be used in a loop to do so.
So basically, we create a 2D array in the generator and I'd like to access the whole slice at once. I could do it with eachcol and eachrow for actual array, but what about the generator?
Here is a test case:
myVec1 = rand(0:4, 2);
myVec2 = rand(0:4, 800);
@btime begin
myMat = [val1 + val2 for val1 in myVec1, val2 in myVec2];
outVec = [sum(myCol) for myCol in eachcol(myMat)];
end
@btime begin
myGen = (val1 + val2 for val1 in myVec1, val2 in myVec2);
outVec = [sum(myCol) for myCol in Iterators.partition(myGen, 2)];
end
The solution by @Bogumił Kamiński indeed works, yet in practice, for some reason, it creates more allocations while the motivation was to reduce it.