Matlab在python中的排序函数

时间:2022-06-09 21:22:12

Let´s say that i have a matrix a in matlab and a vector b as follows:

假设我在matlab和向量b中有一个矩阵a,如下所示:

a =
     2     1     1
     3     3     1
     3     2     2

b =
     1     3     2

Using matlab´s sort function I can achieve the following:

使用matlab的排序功能,我可以实现以下功能:

[n idx] = sort(b)

n =
     1     2     3

idx =
     1     3     2

anew = a(idx,idx)

anew =

     2     1     1
     3     2     2
     3     1     3

Now, I want to do exactly the same in python. My attempt:

现在,我想在python中做同样的事情。我的尝试:

a = np.array([[2,1,1],[3,3,1],[3,2,2]])

b = [0,2,1]

idx = [i[0] for i in sorted(enumerate(b), key=lambda x:x[1])]

The problem is that I cannot find a way to build the anew matrix as I did using Matlab. I have tried:

问题是我找不到像使用Matlab那样建立新矩阵的方法。我努力了:

anew=a[idx]

anew

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

As you can see the results (matlab vs python) are not the same.

正如你所看到的结果(matlab与python)不一样。

Any tip?

1 个解决方案

#1


2  

numpy has advanced indexing, so directly use idx on both dimension will trigger advanced indexing and the result will be a 1d array; To index in a cross product fashion, you'll need to use np.ix_ to construct the index mesh, as stated from the docs:

numpy具有高级索引,因此在两个维度上直接使用idx将触发高级索引,结果将是1d数组;要以交叉产品方式进行索引,您需要使用np.ix_来构造索引网格,如文档中所述:

Using ix_ one can quickly construct index arrays that will index the cross product.

使用ix_可以快速构建索引数组,以索引交叉产品。

a[np.ix_(idx, idx)]

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

Or another option is slice in two steps:

或者另一种选择是分两步进行切片:

a[idx][:,idx]
#array([[2, 1, 1],
#       [3, 2, 2],
#       [3, 1, 3]])

#1


2  

numpy has advanced indexing, so directly use idx on both dimension will trigger advanced indexing and the result will be a 1d array; To index in a cross product fashion, you'll need to use np.ix_ to construct the index mesh, as stated from the docs:

numpy具有高级索引,因此在两个维度上直接使用idx将触发高级索引,结果将是1d数组;要以交叉产品方式进行索引,您需要使用np.ix_来构造索引网格,如文档中所述:

Using ix_ one can quickly construct index arrays that will index the cross product.

使用ix_可以快速构建索引数组,以索引交叉产品。

a[np.ix_(idx, idx)]

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

Or another option is slice in two steps:

或者另一种选择是分两步进行切片:

a[idx][:,idx]
#array([[2, 1, 1],
#       [3, 2, 2],
#       [3, 1, 3]])