2017-07-18 59 views
0

Let's说我在MATLAB矩阵a和矢量b如下:Matlab的排序功能相当于在Python

a = 
    2  1  1 
    3  3  1 
    3  2  2 

b = 
    1  3  2 

使用matlab's sort功能,我可以实现以下目标:

[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 

现在,我想在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])] 

的问题是,我无法找到一个方法来建立anew矩阵像我一样用Matlab。我试过了:

anew=a[idx] 

anew 

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

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

任何提示?

回答

1

numpy有高级索引,所以直接使用idx这两个维都会触发高级索引,结果会是1d数组;以跨产品的时尚指数,你需要使用np.ix_构建指数网,从文档中指出:

使用ix_一个可以快速构建索引数组是将指数 积。

a[np.ix_(idx, idx)] 

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

或者另一种选择是片分为两步:

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

谢谢你,我真的很感激 – sera