【问题标题】:Python equivalent of Matlab shiftdim()Python 等价于 Matlab shiftdim()
【发布时间】:2021-08-07 13:39:23
【问题描述】:

我目前正在将一些Matlab代码转换为Python,我想知道是否有与Matlab的shiftdim(A, n)类似的功能

B = shiftdim(A,n) 将数组 A 的维度移动 n 个位置。当 n 为正整数时,shiftdim 将维度向左移动,当 n 为负整数时,将维度向右移动。例如,如果 A 是一个 2×3×4 数组,则 shiftdim(A,2) 返回一个 4×2×3 数组。

【问题讨论】:

  • 在 Python 中,将代码写成矩阵运算的重要性要小得多。在 Matlab 中,您希望尽可能避免循环,因为它们很慢。如果 shiftdim 用于将您的问题转换为矩阵运算,那么可能有一种不同的、更 Pythonic 的方法。
  • @user_na,他可能正在使用具有类似矩阵功能的numpy。
  • 似乎np.transpose 会处理它。但是要得出正确的顺序需要一些思考。从文档开始,并尝试一些小例子。例如arr.transpose(2,0,1)

标签: python matlab numpy equivalent


【解决方案1】:

如果你使用 numpy,你可以使用np.moveaxis

来自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.

【讨论】:

    【解决方案2】:

    shiftdim 的功能比移动轴要复杂一些。

    • 对于输入 shiftdim(A, n),如果 n 为正数,则将轴向左移动 n(即,旋转),但如果 n 为负数,则将轴向右移动并附加大小为 1 的尾随维度。李>
    • 对于输入 shiftdim(A),删除任何大小为 1 的尾随尺寸。
    from collections import deque
    import numpy as np
    
    def shiftdim(array, n=None):
        if n is not None:
            if n >= 0:
                axes = tuple(range(len(array.shape)))
                new_axes = deque(axes)
                new_axes.rotate(n)
                return np.moveaxis(array, axes, tuple(new_axes))
            return np.expand_dims(array, axis=tuple(range(-n)))
        else:
            idx = 0
            for dim in array.shape:
                if dim == 1:
                    idx += 1
                else:
                    break
            axes = tuple(range(idx))
            # Note that this returns a tuple of 2 results
            return np.squeeze(array, axis=axes), len(axes)
    

    与 Matlab 文档相同的示例

    a = np.random.uniform(size=(4, 2, 3, 5))
    print(shiftdim(a, 2).shape)      # prints (3, 5, 4, 2)
    print(shiftdim(a, -2).shape)     # prints (1, 1, 4, 2, 3, 5)
    
    a = np.random.uniform(size=(1, 1, 3, 2, 4))
    b, nshifts = shiftdim(a)
    print(nshifts)                   # prints 2
    print(b.shape)                   # prints (3, 2, 4)
    

    【讨论】:

      猜你喜欢
      • 2012-10-18
      • 2022-11-02
      • 2014-10-17
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 2014-09-07
      • 2016-11-02
      • 1970-01-01
      相关资源
      最近更新 更多