在 MATLAB 中对 3D 数组进行排序和索引
Sorting and indexing 3D arrays in MATLAB
设 A 和 B 为大小相同的 3D 数组。我想对 A 的每一页进行排序并(当然是快速有效地)排列 B,使其新索引将对应于 A 的新索引。即我想以与 As 相同的方式使 Bs 条目排列。
天真的做法是
[sortedA,idx] = sort(A);
newB=B(idx);
但是,这不起作用,因为 A(idx) 不等于 sortedA。 A(idx) 改为制作第一个排序页面的所有页面副本。
这种情况的解决方法是什么?
镜头 #1(在每个 3D page/slice 中沿列排序)
%// 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 中的所有元素进行排序 page/slice)
%// 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))
设 A 和 B 为大小相同的 3D 数组。我想对 A 的每一页进行排序并(当然是快速有效地)排列 B,使其新索引将对应于 A 的新索引。即我想以与 As 相同的方式使 Bs 条目排列。
天真的做法是
[sortedA,idx] = sort(A);
newB=B(idx);
但是,这不起作用,因为 A(idx) 不等于 sortedA。 A(idx) 改为制作第一个排序页面的所有页面副本。
这种情况的解决方法是什么?
镜头 #1(在每个 3D page/slice 中沿列排序)
%// 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 中的所有元素进行排序 page/slice)
%// 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))