用另一个矩阵对一个矩阵进行排序 [英] Sort a matrix with another matrix

查看:153
本文介绍了用另一个矩阵对一个矩阵进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个矩阵A,并且对该矩阵的行进行了排序.如何在矩阵B(当然是相同大小)上复制相同的顺序?

Suppose I have a matrix A and I sort the rows of this matrix. How do I replicate the same ordering on a matrix B (same size of course)?

例如

A = rand(3,4);
[val ind] = sort(A,2);
B = rand(3,4);
%// Reorder the elements of B according to the reordering of A

这是我想出的最好的

m = size(A,1);
B = B(bsxfun(@plus,(ind-1)*m,(1:m)'));

出于好奇,还有其他选择吗?

Out of curiosity, any alternatives?

更新:乔纳斯的出色解决方案在2008a(XP)上进行了简介:

Update: Jonas' excellent solution profiled on 2008a (XP):

0.048524       1.4632       1.4791        1.195       1.0662        1.108       1.0082      0.96335      0.93155      0.90532      0.88976

n = 2m

0.63202       1.3029       1.1112       1.0501      0.94703      0.92847      0.90411       0.8849       0.8667      0.92098      0.85569

由于推荐答案

一种更清晰的方法是使用循环

A somewhat clearer way to do this is to use a loop

A = rand(3,4);
B = rand(3,4);
[sortedA,ind] = sort(A,2);

for r = 1:size(A,1)
   B(r,:) = B(r,ind(r,:));
end

有趣的是,对于较小(小于12行)和较大(大于700行)正方形阵列(r2010a,OS X),循环版本的速度更快.相对于行的列数越多,循环执行得越好.

Interestingly, the loop version is faster for small (<12 rows) and large (>~700 rows) square arrays (r2010a, OS X). The more columns there are relative to rows, the better the loop performs.

这是我迅速破解以进行测试的代码:

Here's the code I quickly hacked up for testing:

siz = 10:100:1010;
tt = zeros(100,2,length(siz));

for s = siz
    for k = 1:100

        A = rand(s,1*s);
        B = rand(s,1*s);
        [sortedA,ind] = sort(A,2);

        tic;
        for r = 1:size(A,1)
            B(r,:) = B(r,ind(r,:));
        end,tt(k,1,s==siz) = toc;

        tic;
        m = size(A,1);
        B = B(bsxfun(@plus,(ind-1)*m,(1:m).'));
        tt(k,2,s==siz) = toc;

    end
end

m = squeeze(mean(tt,1));

m(1,:)./m(2,:)

对于正方形阵列

ans =

    0.7149    2.1508    1.2203    1.4684    1.2339    1.1855    1.0212    1.0201    0.8770       0.8584    0.8405

列数是行数(行数相同)的两倍

For twice as many columns as there are rows (same number of rows)

ans =

    0.8431    1.2874    1.3550    1.1311    0.9979    0.9921    0.8263    0.7697    0.6856    0.7004    0.7314

这篇关于用另一个矩阵对一个矩阵进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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