【问题标题】:Matlab's sort function in pythonpython中的matlab排序函数
【发布时间】:2017-07-18 22:08:27
【问题描述】:

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

a =
     2     1     1
     3     3     1
     3     2     2

b =
     1     3     2

使用matlab的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])]

问题是我找不到像使用 Matlab 那样构建anew 矩阵的方法。我试过了:

anew=a[idx]

anew

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

如您所见,结果(matlab vs python)不一样。

有什么建议吗?

【问题讨论】:

    标签: python arrays matlab sorting indexing


    【解决方案1】:

    numpy 具有高级索引,因此直接在两个维度上使用idx 将触发高级索引,结果将是一维数组;要以交叉产品的方式进行索引,您需要使用 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]])
    

    【讨论】:

    • 谢谢你我真的很感激
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 2015-06-19
    • 2012-07-15
    • 2018-08-15
    相关资源
    最近更新 更多