Assign rank to numbers in a vector
Instead of sorting, I suggest you use unique
:
[~, ~, ranking] = unique(x);
It also sorts the vector but maps identical values to the same index. This way identical elements in the original vector get the same rank. For instance, if x = [5 2 3 1 3]
, we get:
ranking =
4 2 3 1 3
If you want an "average" rank, you could use accumarray
in combination with the information obtained both from unique
and from sort
, so do the following instead:
[~, ~, idx_u] = unique(x);
[~, idx_s] = sort(x);
mean_ranks = accumarray(idx_u(:), idx_s(idx_s), [], @mean);
ranking = mean_ranks(idx_u);
In our example we would get:
ranking =
1.0000
2.0000
3.5000
5.0000
3.5000
Note that both values 3 got the average rank of 3.5, as they shared ranks 3 and 4.