下面的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
在numpy中构造数组的方式与在MATLAB中不同。在
其中MATLAB数组是
(y, x, z)
,numpy数组是(z, y, x)
。您的3d numpy数组是一系列“堆叠”的2d数组,所以您索引的是“outside->;inside”(缺少更好的术语)。下面是数组定义的扩展,因此(希望)这会更有意义:因此:
^{pr2}$B
按预期返回33
。在如果你想用一种不那么费心的方法来索引数组,可以考虑像在MATLAB中那样生成它。在
MATLAB和Python索引不同。为了研究这个问题,让我们创建一个
1
到8
的线性数组,然后reshape
得到每种语言中2
-by-2
矩阵:MATLAB软件:
它回来了
^{pr2}$Python:
它回来了
首先你应该注意到的是前两个维度已经切换。这是因为MATLAB使用列主索引,这意味着我们首先对列进行倒计时,而Python使用行主索引,因此它首先跨行计数。在
现在让我们尝试索引它们。让我们试着沿着不同的维度切片。在MATLAB中,我知道如何从三维空间中提取一部分
现在让我们在Python中尝试同样的方法
所以这完全不同。为了得到MATLAB的“等价物”,我们需要
现在,它返回MATLAB版本的转置,由于row major与column major的差异,这是预期的。在
那么这对于索引来说意味着什么呢?看起来Python将主索引放在末尾,这是MALTAB的反面。在
假设我在MATLAB中索引如下
现在要从Python获得
7
,我们应该去这是MATLAB语法的颠倒。请注意,这是相反的,因为我们在创建Python矩阵时考虑了行的主要顺序。如果您像在代码中那样创建它,那么就必须交换最后两个索引,这样就可以像Ander在注释中建议的那样首先正确地创建矩阵。在
我认为纽比用“row major”或“column major”来描述这两个词,比仅仅称之为“row major”或“column major”更好:
一些gif来说明区别:第一个是row major(python/c),第二个是column major(MATLAB/Fortran)
相关问题 更多 >
编程相关推荐