代码之家  ›  专栏  ›  技术社区  ›  Gabriel

用Matlab解释MATLAB索引/切片

  •  2
  • Gabriel  · 技术社区  · 7 年前

    我正在把一些Matlab代码转换成Python,我发现一行我听不懂:

    Y = reshape(X(j+(1:a*b),:),[b,a,p])
    

    我知道 reshape 函数有一个 numpy analog 我读过 Matrix Indexing in MATLAB 文档,但我似乎无法理解该行,无法将其转换为 numpy 索引/切片。

    我试过了 online converter OMPC 但它使用 functions that are not defined outside of it (像 mslice ):

    Y = reshape(X(j + (mslice[1:a * b]), mslice[:]), mcat([b, a, p]))
    

    我也试过 SMOP converter 但结果也很难理解:

    Y = reshape(X(j + (arange(1, dot(a, b))), arange()), concat([b, a, p]))
    

    你能用简单的Matlab解释一下 麻木的 索引/切片规则?

    2 回复  |  直到 7 年前
        1
  •  2
  •   anishtain4    7 年前
    Y = X[j+np.arange(a*b),:].reshape((b,a,p))
    

    在不知道您到底想要什么的情况下,这是将Matlab行翻译成Python的过程。

    注意,Matlab索引从1开始,而Numpy索引从0开始。所以根据其他的线,内线可以是 np.arange(a*b) np.arange(1,a*b) .

    你也不需要使用第二个索引 X 如此 X[1,:]==X[1] True

        2
  •  1
  •   hpaulj    7 年前

    在八度音阶中:

    >> 1:3*3
    ans =
       1   2   3   4   5   6   7   8   9
    

    在纽比伊普顿:

    In [8]: np.arange(1,10)
    Out[8]: array([1, 2, 3, 4, 5, 6, 7, 8, 9])
    In [9]: np.arange(3*3)
    Out[9]: array([0, 1, 2, 3, 4, 5, 6, 7, 8])