Efficient way to shift 2D-matrices in both directions?

前端 未结 4 1785
离开以前
离开以前 2021-02-07 15:29

Given a two dimensional matrix, e.g.

l = [[1,1,1],
     [2,5,2],
     [3,3,3]])

What is the most efficient way of implementing a shift operatio

4条回答
  •  不要未来只要你来
    2021-02-07 15:54

    Numpy provides a method called roll() to shift entries.

    >>> import numpy as np
    >>> x = np.arange(9)
    >>> x = x.reshape(3, 3)
    >>> print(x)
    
    [[0 1 2]
     [3 4 5]
     [6 7 8]]
    
    >>> x = np.roll(x, -1, axis=0) # up
    >>> print(x)
    
    [[3 4 5]
     [6 7 8]
     [0 1 2]]
    
    >>> x = np.roll(x, 1, axis=0) # down
    >>> print(x)
    
    [[0 1 2]
     [3 4 5]
     [6 7 8]]
    
    >>> x = np.roll(x, 2, axis=1) # right
    >>> print(x)
    
    [[1 2 0]
     [4 5 3]
     [7 8 6]]
    
    >>> x = np.roll(x, -2, axis=1) # left
    >>> print(x)    
    
    [[0 1 2]
     [3 4 5]
     [6 7 8]]
    

    I guess that Numpy will be pretty efficient compared to most solutions
    in terms of matrix operations and you won't be bound to a 2 dimensional matrix.

提交回复
热议问题