Reputation: 161
Say I have a large array:
A = 2*np.ones([100, 100, 100])
I want to do some calculations on it, for example:
def squared_elements(M):
yield M**2
I choose to use a generator function because my array is very big and I don't need all the results. As a matter of fact, I only need, say, a cube of length 10 at the center of the matrix.
If it was a normal function, I could just write:
result = squared_elements(A)[45:55, 45:55, 45:55]
However, generators are not subscriptable, so this last expression doesn't work.
How can I get the same result
using my generator function?
Upvotes: 0
Views: 227
Reputation: 899
result = next(squared_elements(A))
result[45:55, 45:55, 45:55]
You can slice the subset before squaring
def squared_elements(A, slice_):
return A[slice_] ** 2
result = squared_elements(A, [slice(45, 55), slice(45, 55), slice(45, 55)])
I hope this helps!
Upvotes: 1