Question regarding Sortrows usage with anonymous function


#1

Hi,

I am trying to understand the command sortrows using the option “by”.

If I have a 3x2 array v:

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

If I want to sort it by the second column, then I have to do:

u=sortrows(v, by=x -> x[2])

I understand that the construction x -> x is an anonymous function.

However, why the construction x -> x[2] means that it should sort array v by the 2nd column ? Can someone provide a little bit more of detail about it ?

thank you


#2

Checking the docs for sortrows! tells you to check the docs for sort! to find out about keyword arguments:

help?> sort!
...

The by keyword lets you provide a function that will be applied to each element before comparison;
...                                             

So as the elements are rows x -> x[2] will return the entry in the second column of the row currently being sorted. And that will be used for comparison.


#3

Does this help?

julia> function by(x)
           println("checking: $x and extracting $(x[2])")
           x[2]
       end
by (generic function with 1 method)

julia> v = [1 2; 2 4; 3 1]
3×2 Array{Int64,2}:
 1  2
 2  4
 3  1

julia> sortrows(v, by=by)
checking: [2, 4] and extracting 4
checking: [1, 2] and extracting 2
checking: [1, 2] and extracting 2
checking: [2, 4] and extracting 4
checking: [3, 1] and extracting 1
checking: [2, 4] and extracting 4
checking: [2, 4] and extracting 4
checking: [3, 1] and extracting 1
checking: [3, 1] and extracting 1
checking: [1, 2] and extracting 2
checking: [1, 2] and extracting 2
checking: [3, 1] and extracting 1
3×2 Array{Int64,2}:
 3  1
 1  2
 2  4

#4

thanks, it is very clear now.