numpy.matrix.strides#
attribute
- matrix.strides#
Tuple of bytes to step in each dimension when traversing an array.
The byte offset of element
(i[0],i[1],...,i[n])
in an arrayais:offset=sum(np.array(i)*a.strides)
A more detailed explanation of strides can be found inThe N-dimensional array (ndarray).
Warning
Setting
arr.strides
is discouraged and may be deprecated in thefuture.numpy.lib.stride_tricks.as_strided
should be preferredto create a new view of the same data in a safer way.Notes
Imagine an array of 32-bit integers (each 4 bytes):
x=np.array([[0,1,2,3,4],[5,6,7,8,9]],dtype=np.int32)
This array is stored in memory as 40 bytes, one after the other(known as a contiguous block of memory). The strides of an array tellus how many bytes we have to skip in memory to move to the next positionalong a certain axis. For example, we have to skip 4 bytes (1 value) tomove to the next column, but 20 bytes (5 values) to get to the sameposition in the next row. As such, the strides for the arrayx will be
(20,4)
.Examples
>>>importnumpyasnp>>>y=np.reshape(np.arange(2*3*4,dtype=np.int32),(2,3,4))>>>yarray([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]], dtype=np.int32)>>>y.strides(48, 16, 4)>>>y[1,1,1]np.int32(17)>>>offset=sum(y.strides*np.array((1,1,1)))>>>offset//y.itemsizenp.int64(17)
>>>x=np.reshape(np.arange(5*6*7*8,dtype=np.int32),(5,6,7,8))>>>x=x.transpose(2,3,1,0)>>>x.strides(32, 4, 224, 1344)>>>i=np.array([3,5,2,2],dtype=np.int32)>>>offset=sum(i*x.strides)>>>x[3,5,2,2]np.int32(813)>>>offset//x.itemsizenp.int64(813)