Lepidopterist
Lepidopterist

Reputation: 411

Sorting and indexing 3D arrays in MATLAB

Let A and B be 3D arrays of the same size. I would like to sort each page of A and (quickly and efficiently, of course) permute B such that its new indices will correspond to the new indices of A. I.e. I want to make Bs entry permute in the same manner as As.

The naive approach is to do

  [sortedA,idx] = sort(A);
    newB=B(idx);

However, this does not work because A(idx) is not equal to sortedA. A(idx) instead makes all the pages copies of the first sorted page.

What is the solution in this case?

Upvotes: 2

Views: 107

Answers (1)

Divakar
Divakar

Reputation: 221564

Shot #1 (Sorting along columns in each 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)

Shot #2 (Sorting for all elements in each 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))

Upvotes: 1

Related Questions