Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: find maximum along columns in array

Tags:

julia

Suppose we have an array defined like this:

a=[1 2; 3 4; 5 5; 7 9; 1 2];

In Matlab, we could find the maximum values by writing:

 [x y] = max(a)
   x =
     7     9

In Julia, we could use:

  a=[1 2; 3 4; 5 5; 7 9; 1 2]
  findmax(a,1)

returning:

 ([7 9],

  [4 9])

However, I am interested not only in finding [7 9] for the two columns, but also their relative position within each column, like [4, 4]. Of course, I can write a bit more of coding lines, but can I do it directly with findmax?

like image 322
pp11 Avatar asked May 12 '17 16:05

pp11


2 Answers

The second matrix returned by findmax is the linear index of the locations of the maxima over the entire array. You want the position within each column; to get that, you can convert the linear indices into subscripts with ind2sub. Then the first element of the subscript tuple is your row index.

julia> vals, inds = findmax(a, 1)
(
[7 9],

[4 9])

julia> map(x->ind2sub(a, x), inds)
1×2 Array{Tuple{Int64,Int64},2}:
 (4,1)  (4,2)

julia> map(x->ind2sub(a, x)[1], inds)
1×2 Array{Int64,2}:
 4  4
like image 195
mbauman Avatar answered Nov 18 '22 00:11

mbauman


This is mentioned in the comments but I figured I'd do a response that's easy to see. I have version 1.0.3, so I don't know what's the earliest version that allows this. But now you can just do

julia> findmax(a) #Returns 2D index of overall maximum value
(9, CartesianIndex(4, 2))

julia> findmax(a[:,1]) #Returns 1D index of max value in column 1
(7, 4)

julia> findmax(a[:,2]) #Returns 1D index of max value in column 2
(9, 4)

Hope this makes things easier.

like image 2
Bebotron Avatar answered Nov 18 '22 01:11

Bebotron