Tuesday, April 13, 2010

rotating numpy arrays

finally found a good way to operate on rotated numpy arrays. numpy.roll returns the array that i would need as an operand, but it makes a copy so i would need 3 times the memory footprint of the original array by the time i do the operation. slicing makes a view, not a copy, so it will only require 2 times. (i think; maybe it would still need as much due to the concatenation. should i look at numpy.lib.stride_tricks? i think numpy.take still makes a copy, too.) r = 2 # roll 2 index steps np.concatenate((a[:,r:]- a[:,:-r],a[:,:r]-a[:,-r:]),axis=1) the axis=1 makes it equivalent to hstack; axis=0 would be vstack (make sure to change the slices to r:,: etc.) EDIT: i don't know why i've been so thick-headed about this. the way to control (and conserve) memory is to allocate it first and use a slice/fancy indexing to access it. dp = n.empty_like(p) dp[:,:-1] = p[:,1:]-p[:,:-1]; dp[:,-1:] = p[:,:1]-p[:,-1:]

No comments: