"Desort" vector (deselect)

In Matlab, sort returns both a sorted vector and an index vector showing which vector element was moved, where:

 [v, ix] = sort(u); 

Here v is a vector containing all elements of u , but sorted. ix is a vector showing the initial position of each element v in u . Using Matlab syntax, u(ix) == v .

My question is: How to get u from v and ix ?

Of course, I could just 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 get the feeling that there is a more elegant, one-position, vectorized way to do this.


If you are wondering why you need to do this and not just use u : I tried to implement the Benjamini-Hochberg procedure, which corrects each element of the vector based on its position after sorting, but restores the original order after tuning was important to me.

+4
sorting vectorization matlab
source share
1 answer

Decision:

 w(ix) = v; 

This is a valid Matlab operation, provided that w either not less than v or has not yet been declared.

Example:

 >> 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 understood the solution when I introduced the question, and thought it might be useful to someone.)

+5
source share

All Articles