“分类"向量(撤消排序) [英] "Desort" a vector (undo a sorting)
问题描述
在Matlab中,sort
返回排序后的向量和索引向量,该向量显示哪个向量元素已移动到哪里:
In Matlab, sort
returns both the sorted vector and an index vector showing which vector element has been moved where:
[v, ix] = sort(u);
在这里,v
是包含u
的所有元素但已排序的向量. ix
是显示u
中v
的每个元素的原始位置的向量.使用Matlab的语法u(ix) == v
.
Here, v
is a vector containing all the elements of u
, but sorted. ix
is a vector showing the original position of each element of v
in u
. Using Matlab's syntax, u(ix) == v
.
我的问题:如何从v
和ix
获取u
?
当然,我可以简单地使用:
Of course, I could simply use:
w = zero(size(v));
for i = 1:length(v)
w(ix(i)) = v(i)
end
if nnz(w == u) == length(u)
print('Success!');
else
print('Failed!');
end
但是我有一种舌尖的感觉,那就是有一种更加优雅,单一陈述,矢量化的方式来实现这一目标.
But I am having this tip-of-the-tongue feeling that there is a more elegant, single-statement, vectorized way of doing this.
如果您想知道为什么需要这样做而不是仅使用u
:我正在尝试实现Benjamini-Hochberg过程,该过程根据向量的位置来调整向量的每个元素排序后,但是调整后恢复原始顺序对我来说很重要.
If you are wondering why one would need to do this instead of just using u
: I was trying to implement the Benjamini-Hochberg procedure which adjusts each element of the vector based on its position after sorting, but recovering the original order after adjusting was important for me.
推荐答案
解决方案是:
w(ix) = v;
这是有效的Matlab操作,条件是w
至少与v
一样大,或者尚未声明.
This is a valid Matlab operation provided that w
is either at least as big as v
, or not yet declared.
示例:
>> u = [4 8 10 6 2];
>> [v, ix] = sort(u)
v = 2 4 6 8 10
ix = 5 1 4 2 3
>> u(ix)
ans = 2 4 6 8 10
>> w(ix) = v
w = 4 8 10 6 2
(为平凡的问题回答道歉,但是我在输入问题时意识到了解决方案,并认为这可能对某人有用.)
(Apologies for the trivial question-answer, but I realized the solution as I was typing the question, and thought it might be useful to someone.)
这篇关于“分类"向量(撤消排序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!