7
votes

This question is basically an extension of that question.

I have a matrix A in Matlab and want to sort that matrix along one dimension:

A = rand(3,3,5); [B idx] = sort(A,3);

Now idx is a matrix containing the "sorted" indices. How can i get back the matrix A using only B and idx?

The answer of the original question doesn't work for matrices, unfortunately.

1
Have you tried w(ix,:)=v, where : represents "ignored" dimensions? - Crowley
Do you mean in my case something like: w(:,:,idx) = B? That doesn't work due to "Subscripted assignment dimension mismatch." - Ethunxxx
w(idx)=B works but it is incorrect - shamalaia

1 Answers

4
votes

You need to sort the indices idxto get back the original indices. Rest of the work would involve getting the formatted row and column indices corresponding to all those dim-3 indices. The implementation would look something like this -

[~,dim3idx] = sort(idx,3);

[m,n,r] = size(B);
[rowidx,colidx,~] = ndgrid(1:m,1:n,1:r);

Aout = B(sub2ind(size(B),rowidx,colidx,dim3idx))

Please note that for performance, one can get the linear indices generated by sub2ind alternatively with bsxfun directly from the size parameters and thus also avoid ndgrid, like so -

Aout = B(bsxfun(@plus,bsxfun(@plus,(1:m)',m*(0:n-1)),m*n*(dim3idx-1)))