首页 > 解决方案 > 在 MATLAB 和 Python 中重塑和索引

问题描述

我在 Matlab 中有一个代码,需要用 Python 翻译。这里有一点,形状和索引非常重要,因为它适用于张量。我有点困惑,因为它似乎order='F'在 python中使用就足够了reshape()。但是当我使用 3D 数据时,我注意到它不起作用。例如 ifA是 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 和 Python 中的 SVD 给出了不同的结果。那么,有没有办法解决这个问题?

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

标签: pythonarraysmatlabreshapetensor

解决方案


在 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)

推荐阅读