Search code examples
pythonmatlabnumpyequivalent

Python equivalent of Matlab shiftdim()


I am currently converting some Matlab code to Python and I am wondering if there is a similar function to Matlab's shiftdim(A, n)

B = shiftdim(A,n) shifts the dimensions of an array A by n positions. shiftdim shifts the dimensions to the left when n is a positive integer and to the right when n is a negative integer. For example, if A is a 2-by-3-by-4 array, then shiftdim(A,2) returns a 4-by-2-by-3 array.


Solution

  • If you use numpy you can use np.moveaxis.

    From the docs:

    >>> x = np.zeros((3, 4, 5))
    >>> np.moveaxis(x, 0, -1).shape
    (4, 5, 3)
    >>> np.moveaxis(x, -1, 0).shape
    (5, 3, 4)
    

    numpy.moveaxis(a, source, destination)[source]

    Parameters
    
    a:        np.ndarray 
              The array whose axes should be reordered.
    
    source:   int or sequence of int
              Original positions of the axes to move. These must be unique.
    
    destination: int or sequence of int
                 Destination positions for each of the original axes. 
                 These must also be unique.