让A和B成为相同大小的3D阵列。我想对A的每一页进行排序,并且(当然快速有效地)对B进行排序,使其新指数对应于A的新指数。我希望以与As相同的方式进行Bs条目置换。
天真的做法是
[sortedA,idx] = sort(A);
newB=B(idx);
但是,这不起作用,因为A(idx)不等于sortedA。 A(idx)代替第一个排序页面的所有页面副本。
这种情况下的解决方案是什么?
答案 0 :(得分:1)
拍摄#1(沿每个3D页面/切片中的列排序)
%// Get size of A
[m,n,r] = size(A)
%// Sort A along each column and get the corresponding sorting indices
[sortedA,idx] = sort(A)
%// Get the corresponding sorting indices for B and get the new B with them
idxB = bsxfun(@plus,bsxfun(@plus,idx,[0:n-1]*m),permute([0:r-1]*m*n,[1 3 2]))
newB = B(idxB)
拍摄#2(对每个3D页面/切片中的所有元素进行排序)
%// Get size of A
[m,n,r] = size(A)
%// Reshape A into a 2D array and then sort it, and
%// also get the corresponding sorting indices
[sortedA,idx] = sort(reshape(A,[],r))
%// Get corresponding sorting indices for B, index into B with it,
%// reshape it and have the desired re-arranged B
idxB = bsxfun(@plus,idx,[0:r-1]*m*n)
newB = reshape(B(idxB),size(B))