Search code examples
matlabordinal

Matlab - determine column wise the ordinal rank of values in a matrix


I have following mxn matrix:

X = [-0.0061   -0.0108   -0.0098;
    0.0092    0.0237    0.0114;
   -0.0026   -0.0082    0.0035;
   -0.0033    0.0257   -0.0106]

What i want to do is to assign the ordinal rank within each column, i.e. to get following matrix Y.

Y = [1  1   2;
     4  3   4;
     3  2   3;
     2  4   1]

I tried it with [~,~,ranking] = unique(X) but unfortunately there it considers all matrix elements and ranks them ordinally and does not do the job column wise. Furthermore it puts the ranks in a column vector and not in the shape of upper Y matrix.

Thanks for any help!


Solution

  • Just use the second output of sort. Thanks to @beaker for the correction (see comments below);

    [~, result] = sort(X, 1);
    [~, result] = sort(result, 1);