![]() |
用另一个矩阵排序一个矩阵
假设我有一个矩阵A并且对该矩阵的行进行了排序。如何在矩阵B (当然是相同大小)上复制相同的顺序?
例如 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)')); 出于好奇,还有其他选择吗? [B]更新:[/B] [URL="https://stackoverflow.com/questions/2679022/sort-a-matrix-with-another-matrix/2679517#2679517"]Jonas[/URL]在2008a(XP)上[URL="https://stackoverflow.com/questions/2679022/sort-a-matrix-with-another-matrix/2679517#2679517"]的出色解决方案[/URL]简介: [B] n = n [/B] 0.048524 1.4632 1.4791 1.195 1.0662 1.108 1.0082 0.96335 0.93155 0.90532 0.88976 [B] n = 2m [/B] 0.63202 1.3029 1.1112 1.0501 0.94703 0.92847 0.90411 0.8849 0.8667 0.92098 0.85569 它只是表明,由于[URL="http://www.mathworks.com/company/newsletters/news_notes/may03/profiler.html"]JITA[/URL] (也许),对于MATLAB程序员而言,循环不再是[URL="http://www.mathworks.com/company/newsletters/news_notes/may03/profiler.html"]令人厌恶的[/URL]了。 [B]回答:[/B] 一种更清晰的方法是使用循环 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 有趣的是,对于小(〜700行)正方形数组(r2010a,OS X),循环版本更快。相对于行的列数越多,循环执行得越好。 这是我很快破解以进行测试的代码: 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 列数是行数的两倍(行数相同) ans = 0.8431 1.2874 1.3550 1.1311 0.9979 0.9921 0.8263 0.7697 0.6856 0.7004 0.7314 [url=https://stackoverflow.com/questions/2679022]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 04:55。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.