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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With