Skip to content

Instantly share code, notes, and snippets.

@jessstringham
Created November 21, 2017 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessstringham/ffbbcc66bbacc288b510b27cd1045089 to your computer and use it in GitHub Desktop.
Save jessstringham/ffbbcc66bbacc288b510b27cd1045089 to your computer and use it in GitHub Desktop.
import numpy as np
from numpy.lib.stride_tricks import as_strided
# Makes a new matrix like this:
# input: [0, 1, 2, 3]
# output: [[0, 1], [1, 2], [2, 3]]
# But, does it all in memory using `as_strided`, so it's speedy.
# And if you make a mistake, you can see fake numbers
data = np.arange(4)
print(data)
new_data = as_strided(
data,
shape=(
data.shape[0] - 1, # Figure out what size the array should be
2, # I want to add another dimension of size 2
),
strides=(
data.strides[0],
data.strides[0], # not a typo. To move one element over in the 2nd dimension,
# move one step in the first stride direction
),
writeable=False, # eek, as_strided mucks around in memory. Make this read-only to avoid hacking too much.
)
print(new_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment