"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)))
链接地址: http://www.djcxy.com/p/91568.html
上一篇: 删除界面构建器中的顶部和底部布局指南