在 MATLAB 和 Python 中重塑和索引

Reshape and indexing in MATLAB and Python

我在 Matlab 中有一段代码,需要在 Python 中翻译。这里有一点,形状和索引非常重要,因为它适用于张量。我有点困惑,因为似乎在 python reshape() 中使用 order='F' 就足够了。但是当我处理 3D 数据时,我发现它不起作用。例如,如果 A 是 python

中从 1 到 27 的数组
array([[[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9]],

       [[10, 11, 12],
        [13, 14, 15],
        [16, 17, 18]],

       [[19, 20, 21],
        [22, 23, 24],
        [25, 26, 27]]])

如果我执行 A.reshape(3, 9, order='F') 我得到

[[ 1  4  7  2  5  8  3  6  9]
 [10 13 16 11 14 17 12 15 18]
 [19 22 25 20 23 26 21 24 27]]

在 Matlab 中,A = 1:27 重塑为 [3, 3, 3] 然后 [3, 9] 似乎我得到了另一个数组:

1     4     7    10    13    16    19    22    25
2     5     8    11    14    17    20    23    26
3     6     9    12    15    18    21    24    27

Matlab 中的 SVD 和 Python 给出了不同的结果。那么,有没有办法解决这个问题?

也许您知道在 Matlab 中操作多维数组的正确方法 -> python,就像我应该为 arange(1, 13).reshape(3, 4) 这样的数组获得相同的 SVD在 Matlab 1:12 -> reshape(_, [3, 4]) 中或者使用它的正确方法是什么?也许我可以在 python 中以某种方式交换轴以获得与在 Matlab 中相同的结果?或者在 Python 中更改 reshape(x1, x2, x3,...) 中的轴顺序?

在 Matlab 中

A = 1:27;
A = reshape(A,3,3,3);
B = reshape(A,9,3)'
B =

     1     2     3     4     5     6     7     8     9
    10    11    12    13    14    15    16    17    18
    19    20    21    22    23    24    25    26    27
size(B)

ans =

     3     9

在Python

A = np.array(range(1,28))
A = A.reshape(3,3,3)
B = A.reshape(3,9)
B
array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18],
       [19, 20, 21, 22, 23, 24, 25, 26, 27]])
np.shape(B)
 (3, 9)

我遇到了同样的问题,直到我找到这篇维基百科文章:row- and column-major order

Python(和 C)按行主要顺序组织数据数组。正如您在第一个示例代码中所见,元素首先随列增加:

array([[[ 1,  2,  3],
          - - - -> increasing

然后在行

array([[[ 1,  2,  3],
      [ 4,   <--- new element

当所有列和行都已满时,移至下一页。

array([[[ 1,  2,  3],
    [ 4,  5,  6],
    [ 7,  8,  9]],

   [[10,  <-- new element in next page

在 matlab 中(如 fortran)首先增加行,然后是列,依此类推。

对于 N 维数组,它看起来像:

  • Python(主要行 -> 最后一个维度是连续的):[dim1,dim2,...,dimN]
  • Matlab(主要列 -> 第一维是连续的):内存中的相同张量看起来是相反的.. [dimN,...,dim2,dim1]

如果你想导出n-dim。从 python 到 matlab 的数组,最简单的方法是先排列维度: (在 python)

import numpy as np
import scipy.io as sio
A=np.reshape(range(1,28),[3,3,3])
sio.savemat('A',{'A':A})

(在 matlab 中)

load('A.mat')
A=permute(A,[3 2 1]);%dimensions in reverse ordering
reshape(A,9,3)' %gives the same result as A.reshape([3,9]) in python

请注意,(9,3) 和 (3,9) 是有意倒序排列的。