# 用另一个matrix排列matrix

` `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)'));` `

### n = n

` `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` `

### 3 Solutions collect form web for “用另一个matrix排列matrix”

` `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` `

` `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` `

Sort（）按照您sorting的维度返回索引。 您可以显式构造其他维度的索引，使其保持稳定，然后使用线性索引重新排列整个数组。

` `A = rand(3,4); B = A; %// Start with same values so we can programmatically check result [A2 ix2] = sort(A,2); %// ix2 is the index along dimension 2, and we want dimension 1 to remain unchanged ix1 = repmat([1:size(A,1)]', [1 size(A,2)]); %//' %// Convert to linear index equivalent of the reordering of the sort() call ix = sub2ind(size(A), ix1, ix2) %// And apply it B2 = B(ix) ok = isequal(A2, B2) %// confirm reordering` `

` `[val ind]=sort(A); B=B(ind);` `

• 如何在MATLAB中处理函数参数的名称/值对
• 如何使用SIFTalgorithm来计算相似的两幅图像？
• MATLAB的OOP速度慢还是我做错了什么？
• 编写MATLAB代码的好习惯？
• 访问子文件夹中的m文件，而不将其永久添加到path中
• 如何将绘图保存为PDF文件而没有大的空白
• 在MATLAB中，variables真的是双精度默认？
• MATLAB最接近命名空间的是什么？
• 在Matlab中使用i和j作为variables
• 禁止Matlab窗口焦点窃取
• 使用{}和（）（花括号和圆括号）访问单元格元素之间的区别