numpy数组和Matlab矩阵不匹配[3D] [英] Numpy array and Matlab Matrix are mismatching [3D]
问题描述
以下八度代码显示了使用Octave/Matlab的示例3D矩阵
The following octave code shows a sample 3D matrix using Octave/Matlab
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中的数组访问相同的索引时,我得到的值如下所示!
And I need to convert the same matrix using numpy ... unfortunately When I'm trying to access the same index using array in numpy I get different values as shown below!!
import numpy as np
array = np.array([[[1 ,2 ,3],[4 ,5 ,6],[7 ,8 ,9]], [[11 ,22 ,33],[44 ,55 ,66],[77 ,88 ,99]], [[111 ,222 ,333],[444 ,555 ,666],[777 ,888 ,999]]])
>>> array[0,2,1]
8
我还阅读了以下文档,该文档显示了Matlab和Python numpy中矩阵实现之间的区别
Also I read the following document that shows the difference between matrix implementation in Matlab and in Python numpy Numpy for Matlab users but I didn't find a sample 3d array and the mapping of it into Matlab and vice versa!
答案是不同的,例如,使用numpy(0,2,1)访问Matlab中的element(1,3,2)与相同的索引不匹配
the answer is different for example accessing the element(1,3,2) in Matlab doesn't match the same index using numpy (0,2,1)
八度/Matlab
Octave/Matlab
八度:6> A(1,3,2)
ans = 33
Python
Python
>>>数组[0,2,1]
8
推荐答案
在numpy中构造数组的方式与在MATLAB中构造数组的方式不同.
The way your array is constructed in numpy is different than it is in MATLAB.
在您的MATLAB数组为(y, x, z)
的地方,您的numpy数组为(z, y, x)
.您的3d numpy数组是一系列堆叠"的2d数组,因此您要为"outside-> inside"编制索引(因为缺少更好的术语).这是扩展的数组定义,因此(希望如此)更有意义:
Where your MATLAB array is (y, x, z)
, your numpy array is (z, y, x)
. Your 3d numpy array is a series of 'stacked' 2d arrays, so you're indexing "outside->inside" (for lack of a better term). Here's your array definition expanded so this (hopefully) makes a little more sense:
[[[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]]
]
所以:
import numpy as np
A = np.array([[[1 ,2 ,3],[4 ,5 ,6],[7 ,8 ,9]], [[11 ,22 ,33],[44 ,55 ,66],[77 ,88 ,99]], [[111 ,222 ,333],[444 ,555 ,666],[777 ,888 ,999]]])
B = A[1, 0, 2]
B
会按预期返回33
.
如果您想要一种省力的索引数组的方法,请考虑像在MATLAB中一样生成它.
If you want a less mind-bending way to indexing your array, consider generating it as you did in MATLAB.
这篇关于numpy数组和Matlab矩阵不匹配[3D]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!