Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Desort" a matrix. Undo a sorting in Matlab

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.

like image 579
Ethunxxx Avatar asked May 03 '16 08:05

Ethunxxx


1 Answers

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)))
like image 136
Divakar Avatar answered Sep 21 '22 17:09

Divakar