简体   繁体   中英

“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.

You need to sort the indices idx to 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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM