从Matpy顺序从numpy数组中顺序获取数据 [英] Get data sequentially from numpy array in Matlab ordering

查看:125
本文介绍了从Matpy顺序从numpy数组中顺序获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个例子,假设在Matlab中像这样的矩阵a(2,3,2):

As an example, suppose, in Matlab, a Matrix a(2,3,2) like this:

a(:,:,1) =

     1     2     3
     4     5     6


a(:,:,2) =

     7     8     9
    10    11    12

如果我使用mex并顺序访问此矩阵的元素,则会得到以下顺序(最后,是按顺序访问它们的代码):

If I use mex and access the elements of this matrix sequentially, I get the following order (in the end, a code to access them sequentially):

1, 4, 2, 5, 3, 6, 7, 10, 8, 11, 9, 12

现在,如果我在numpy中具有相同的矩阵

Now, if I have the same matrix in numpy

In [2]: np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
Out[2]: 
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]]])

,我可以尝试使用.flatten(...)顺序访问项目(找不到更好的方法-我愿意接受建议). flatten()具有4个排序"选项:

, I could try to use .flatten(...) to access the items sequentially (couldn't find a better way to do it -- I am open to suggestions). flatten() has 4 "ordering" options:

In [4]: a.flatten('F')
Out[4]: array([ 1,  7,  4, 10,  2,  8,  5, 11,  3,  9,  6, 12])

In [5]: a.flatten('C')
Out[5]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

In [6]: a.flatten('A')
Out[6]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

In [7]: a.flatten('K')
Out[7]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

是否有一种优雅的方法来以Matlab顺序访问numpy数组的元素? (在我的实际用例中,这些矩阵很大,因此最好不要复制它们)

Is there an elegant way to access the elements of the numpy array in a Matlab ordering? (in my real use case, these matrix are big, so copiyng them around wouldn't be preferred)

[不是很好,我知道,只是为了测试]

[not great, I know, just for testing]

  1 void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
  2 {
  3         // This just a test: hardcoding the size of `data_input`
  4         int data_input_size = 12;
  5         double *data_input;
  6         const mxArray *batch_data;
  7 
  8         // Gets a pointer to the first element of batch_data
  9         data_input  = mxGetPr(prhs[0]);
 10 
 11         for(int i = 0; i < data_input_size; i++) {
 12                 printf("working_data[i]: %f\n", data_input[i]);
 13         }
 14         plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL);
 15 }

推荐答案

这使许多人从MATLAB进入NumPy/Python时遇到了麻烦.因此,在MATLAB中,索引格式为(column x row x dim3),依此类推.使用NumPy,它是(axis-0, axis-1, axis-2),依此类推.

This bugs a lot of people going into NumPy/Python from MATLAB. So, in MATLAB, the indexing format is (column x row x dim3) and so on. With NumPy, it's (axis-0, axis-1, axis-2) and so on.

使用MATLAB上的示例案例来示意性地显示这一点:

To show this schematically using a sample case on MATLAB :

>> a = reshape(1:27,[3,3,3]);
>> a
a(:,:,1) =

        row
    --------------->
     1     4     7   |         |
     2     5     8   | col     |
     3     6     9   v         |
a(:,:,2) =                     |
    10    13    16             | dim3
    11    14    17             |
    12    15    18             |
a(:,:,3) =                     |
    19    22    25             |
    20    23    26             |
    21    24    27             v

在NumPy上:

In [62]: a = np.arange(27).reshape(3,3,3)

In [63]: a
Out[63]: 

            axis=2
         ---------->
array([[[ 0,  1,  2],   |          |
        [ 3,  4,  5],   | axis=1   |
        [ 6,  7,  8]],  v          |
                                   |
       [[ 9, 10, 11],              |
        [12, 13, 14],              | axis=0
        [15, 16, 17]],             |
                                   |
       [[18, 19, 20],              |
        [21, 22, 23],              |
        [24, 25, 26]]])            v

让我们尝试针对这两个环境中的问题中列出的3D阵列案例,将这些尺寸和轴术语关联起来:

Let's try to correlate these dimensions and axes terminology for the 3D array case listed in the question between these two environments :

MATLAB      NumPy
------------------
cols        axis-1
rows        axis-2
dim3        axis-0

因此,要在NumPy中模拟与MATLAB相同的行为,我们需要在NumPy中的轴为:(1,2,0).结合NumPy存储从最后一个轴到第一个轴(即以相反的顺序)开始的元素的方式,所需的轴顺序为(0,2,1).

Thus, to simulate the same behavior in NumPy as MATLAB, we need the axes in NumPy as : (1,2,0). Together with NumPy's way of storing elements starting from the last axis to the first one i.e. in reversed order, the required axes order would be (0,2,1).

要以这种方式执行轴置换,我们可以使用 np.transpose ,然后对 np.ravel() -

To perform the permuting of axes that way, we could use np.transpose and thereafter use a flattening operation with np.ravel() -

a.transpose(0,2,1).ravel()

样品运行-

In [515]: a
Out[515]: 
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]]])

In [516]: a.transpose(0,2,1) # Permute axes
Out[516]: 
array([[[ 1,  4],
        [ 2,  5],
        [ 3,  6]],

       [[ 7, 10],
        [ 8, 11],
        [ 9, 12]]])

In [517]: a.transpose(0,2,1).ravel() # Flattened array
Out[517]: array([ 1,  4,  2,  5,  3,  6,  7, 10,  8, 11,  9, 12])

这篇关于从Matpy顺序从numpy数组中顺序获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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