Matlab与Python:重塑 [英] Matlab vs Python: Reshape

查看:73
本文介绍了Matlab与Python:重塑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我找到了:

转换MATLAB代码时,可能有必要先重塑 矩阵成线性序列,执行一些索引操作,然后 重新塑形.重塑后(通常)会在同一视图上产生视图 存储,应该有可能相当有效地做到这一点.

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.

请注意,Numpy中整形使用的扫描顺序默认为"C" 订单,而MATLAB使用Fortran订单.如果你只是 转换为线性序列并返回该序列无关紧要.但是如果 您正在从依赖扫描的MATLAB代码转换重塑形状 命令,然后输入以下MATLAB代码:

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

应该成为

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

在Numpy中.

当我在MATLAB中执行操作时,我有一个名为mafs的多维16 * 2数组:

I have a multidimensional 16*2 array called mafs, when I do in MATLAB:

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

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

I get something different than when in python I do:

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

甚至

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

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

Any help on this? Thank you all.

推荐答案

示例:

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

这篇关于Matlab与Python:重塑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆