Numpy数组和Matlab矩阵不匹配[3D]

2024-09-30 06:15:02 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的octave代码显示了一个使用octave/Matlab的3D矩阵示例

octave:1> A=zeros(3,3,3);
octave:2> 
octave:2> A(:,:,1)= [[1 2 3];[4 5 6];[7 8 9]];
octave:3> 
octave:3> A(:,:,2)= [[11 22 33];[44 55 66];[77 88 99]];
octave:4> 
octave:4> A(:,:,3)= [[111 222 333];[444 555 666];[777 888 999]];
octave:5> 
octave:5> 
octave:5> A
A =

ans(:,:,1) =

   1   2   3
   4   5   6
   7   8   9

ans(:,:,2) =

   11   22   33
   44   55   66
   77   88   99

ans(:,:,3) =

   111   222   333
   444   555   666
   777   888   999

octave:6> A(1,3,2)
ans =  33

我需要用numpy转换同一个矩阵。。。不幸的是,当我试图在numpy中使用array访问同一个索引时,我得到了如下所示的不同值!!在

^{pr2}$

我还阅读了下面的文档,它展示了Matlab和PythonNumpyNumpy for Matlab users中的矩阵实现之间的区别,但是我没有找到一个示例3d数组以及它到Matlab中的映射,反之亦然!在

答案是不同的,例如在Matlab中访问元素(1,3,2)与使用numpy(0,2,1)的相同索引不匹配

倍频程/Matlab

倍频程:6>;A(1,3,2)

ans=33

PythonPython

>>>数组[0,2,1]

8


Tags: 代码文档numpy示例forzeros矩阵数组
3条回答

在numpy中构造数组的方式与在MATLAB中不同。在

其中MATLAB数组是(y, x, z),numpy数组是(z, y, x)。您的3d numpy数组是一系列“堆叠”的2d数组,所以您索引的是“outside->;inside”(缺少更好的术语)。下面是数组定义的扩展,因此(希望)这会更有意义:

[[[1, 2, 3],
  [4, 5, 6],        # Z = 0
  [7 ,8 ,9]],
 [[11 ,22 ,33],
  [44 ,55 ,66],     # Z = 1
  [77 ,88 ,99]],
 [[111 ,222 ,333],
  [444 ,555 ,666],  # Z = 2
  [777 ,888 ,999]]
]

因此:

^{pr2}$

B按预期返回33。在

如果你想用一种不那么费心的方法来索引数组,可以考虑像在MATLAB中那样生成它。在

MATLAB和Python索引不同。为了研究这个问题,让我们创建一个18的线性数组,然后reshape得到每种语言中2-by-2矩阵:

MATLAB软件:

M_flat = 1:8
M = reshape(M_flat, [2,2,2])

它回来了

^{pr2}$

Python:

import numpy as np
P_flat = np.array(range(1,9))
P = np.reshape(P, [2,2,2])

它回来了

array([[[1, 2],
        [3, 4]],

       [[5, 6],
        [7, 8]]])

首先你应该注意到的是前两个维度已经切换。这是因为MATLAB使用列主索引,这意味着我们首先对列进行倒计时,而Python使用行主索引,因此它首先跨行计数。在

现在让我们尝试索引它们。让我们试着沿着不同的维度切片。在MATLAB中,我知道如何从三维空间中提取一部分

M(:,:,1)

ans =

   1   3
   2   4

现在让我们在Python中尝试同样的方法

P[:,:,0]

array([[1, 3],
       [5, 7]])

所以这完全不同。为了得到MATLAB的“等价物”,我们需要

P[0,:,:]

array([[1, 2],
       [3, 4]])

现在,它返回MATLAB版本的转置,由于row major与column major的差异,这是预期的。在

那么这对于索引来说意味着什么呢?看起来Python将主索引放在末尾,这是MALTAB的反面。在

假设我在MATLAB中索引如下

M(1,2,2)

ans = 

    7

现在要从Python获得7,我们应该去

P(1,1,0)

这是MATLAB语法的颠倒。请注意,这是相反的,因为我们在创建Python矩阵时考虑了行的主要顺序。如果您像在代码中那样创建它,那么就必须交换最后两个索引,这样就可以像Ander在注释中建议的那样首先正确地创建矩阵。在

我认为纽比用“row major”或“column major”来描述这两个词,比仅仅称之为“row major”或“column major”更好:

‘C’ means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest.

一些gif来说明区别:第一个是row major(python/c),第二个是column major(MATLAB/Fortran)

Python/ C index ordering

MATLAB/Fortran index ordering

相关问题 更多 >

    热门问题