python - Matlab 与 Python : Reshape

标签 python matlab matrix numpy scipy

于是我找到了this :

When converting MATLAB code it might be necessary to first reshape a matrix to a linear sequence, perform some indexing operations and then reshape back. As reshape (usually) produces views onto the same storage, it should be possible to do this fairly efficiently.

Note that the scan order used by reshape in Numpy defaults to the 'C' order, whereas MATLAB uses the Fortran order. If you are simply converting to a linear sequence and back this doesn't matter. But if you are converting reshapes from MATLAB code which relies on the scan order, then this MATLAB code:

z = reshape(x,3,4);

should become

z = x.reshape(3,4,order='F').copy()

in Numpy.

当我在 MATLAB 中这样做时,我有一个名为 mafs 的多维 16*2 数组:

mafs2 = reshape(mafs,[4,4,2]) 

我得到的东西与我在 python 中所做的不同:

mafs2 = reshape(mafs,(4,4,2))

甚至

mafs2 = mafs.reshape((4,4,2),order='F').copy()

对此有任何帮助吗?谢谢大家。

最佳答案

例子:

MATLAB:

>> mafs = [(1:16)' (17:32)']
mafs =
     1    17
     2    18
     3    19
     4    20
     5    21
     6    22
     7    23
     8    24
     9    25
    10    26
    11    27
    12    28
    13    29
    14    30
    15    31
    16    32

>> reshape(mafs,[4 4 2])
ans(:,:,1) =
     1     5     9    13
     2     6    10    14
     3     7    11    15
     4     8    12    16
ans(:,:,2) =
    17    21    25    29
    18    22    26    30
    19    23    27    31
    20    24    28    32

Python:

>>> import numpy as np
>>> mafs = np.c_[np.arange(1,17), np.arange(17,33)]
>>> mafs.shape
(16, 2)
>>> mafs[:,0]
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16])
>>> mafs[:,1]
array([17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32])

>>> r = np.reshape(mafs, (4,4,2), order="F")
>>> r.shape
(4, 4, 2)
>>> r[:,:,0]
array([[ 1,  5,  9, 13],
       [ 2,  6, 10, 14],
       [ 3,  7, 11, 15],
       [ 4,  8, 12, 16]])
>>> r[:,:,1]
array([[17, 21, 25, 29],
       [18, 22, 26, 30],
       [19, 23, 27, 31],
       [20, 24, 28, 32]])

关于python - Matlab 与 Python : Reshape,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11892358/

相关文章:

matlab - Matlab中的函数实现

python - 尝试访问矩阵外部时获取特定值

c++ - Assimp 骨骼动画转换矩阵问题

python - Python 和 Node.js 的不同 WPI v3 结果

python - 使用 Python 从剪贴板解析 XML

python - 交错两个 numpy 1D 阵列用于立体声音频输出

matlab - 在 MATLAB 中,单引号和双引号有什么区别?

将增量为 25 的 'for' 循环从 C 转换为 MATLAB

c++ - OpenCV 矩阵乘法断言在类内部失败,但在外部没有

python - 在 python/GAE 中声明全局变量的问题