I often have to find ranks of values in a list. However, Mathematica does not have built-in functions for that, or may be I'm just not aware of them. I can easily find ranks of a row/column vector. For example, if I have

list1 = RandomInteger[{1, 10}, 10] ;

then Ordering[Ordering[list1]] gives me its rank. I have also written a following function that does my job.

 Rankme[list_] := Module[{rank},
  rank = ConstantArray[0, Length[list]];
  rank[[Ordering[list]]] = Range[1, Length[list]] ;

Rankme[list1] gives me ranks of values in the list1 . However, I am trying to find column-wise ranks of a list that has more than one column. For example, I have

list2 = RandomInteger[{1, 10}, {10, 5}];

I want to find column-wise ranks of values in the list2. How can I do this?


2 Answers 2

rrF = Ordering@Ordering@# &;
crF = Transpose[rrF /@ Transpose[#]] &;

mat = RandomInteger[{1, 10}, {10, 5}];
Row[MatrixForm /@ {mat, crF@mat}]

enter image description here

Update: Using the function colMap suggested by @Mr.Wizard in the comments

colMap[f_][m_?MatrixQ] := (f /@ (m\[Transpose]))\[Transpose] 
(* or Transpose[fn /@ Transpose[m]] *)

colMap[rrF][mat] // MatrixForm

gives same output as crF@mat above.

  • $\begingroup$ Thank you kguler. May be I owe you a couple of cups of coffee. $\endgroup$
    – ramesh
    Commented Feb 10, 2015 at 22:08
  • $\begingroup$ incidentally consider a reusable function colMap[fn_][m_?MatrixQ] := (fn /@ (m\[Transpose]))\[Transpose] (+1) $\endgroup$
    – Mr.Wizard
    Commented Feb 10, 2015 at 22:08
  • $\begingroup$ ramesh, my pleasure. One cup -quad espresso- would be fine:) $\endgroup$
    – kglr
    Commented Feb 10, 2015 at 22:12
  • $\begingroup$ @Mr.Wizard, great idea, thank you. Will update with the colMap function. $\endgroup$
    – kglr
    Commented Feb 10, 2015 at 22:13
Ordering /@ Transpose[RandomVariate[UniformDistribution[{10}], {3, 4}]]
  • $\begingroup$ Thank you for your quick response. It was easy. $\endgroup$
    – ramesh
    Commented Feb 10, 2015 at 22:01
  • $\begingroup$ If it doesn't give you what you want, please explain why. $\endgroup$ Commented Feb 10, 2015 at 22:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.