简体   繁体   English

“Desort”矩阵。 在Matlab中撤消排序

[英]“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: 我在Matlab中有一个矩阵A ,想要沿着一个维度对该矩阵进行排序:

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

Now idx is a matrix containing the "sorted" indices. 现在, idx是一个包含“已排序”索引的矩阵。 How can i get back the matrix A using only B and idx ? 如何仅使用Bidx返回矩阵A

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. 您需要对索引idx进行排序以获取原始索引。 Rest of the work would involve getting the formatted row and column indices corresponding to all those dim-3 indices. 其余的工作将涉及获取与所有那些dim-3索引相对应的格式化的行和列索引。 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 - 请注意,为了提高性能,可以直接从size参数中获取sub2ind生成的线性索引和bsxfun ,从而避免使用ndgrid ,如下所示 -

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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