6
$\begingroup$

I am trying to find the largest and second largest number in each row and column. The largest numbers are easy, but how do I find the second largest?

After I found them I also want to calculate the difference of the two largest numbers in each row and column.

c = {{36, 32, 33, 19}, {10, 8, 7, 20}, {12, 17, 16, 29}, {23, 15, 16, 
    28}};
Max /@ c
Max /@ Transpose[c]
$\endgroup$

2 Answers 2

4
$\begingroup$
#[[Ordering[#, -2]]] & /@ c
#[[Ordering[#, -2]]] & /@ Transpose[c]
$\endgroup$
4
$\begingroup$

Use TakeLargest:

fn = TakeLargest[#, 2] &;

(* Largest in rows *)
fn /@ c
{{36, 33}, {20, 10}, {29, 17}, {28, 23}}
(*Largest in columns *)
fn /@ Transpose@c
{{36, 23}, {32, 17}, {33, 16}, {29, 28}}
$\endgroup$

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.