Julia: find maximum along columns in an array
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)
return:
([7 9],
[4 9])
However, I'm not only interested in finding [7 9] for two columns, but also their relative position in each column, like [4, 4]. Of course, I can write a little more lines of coding, but can I do this directly with findmax?
The second matrix returned findmax
is the linear index of the maximum locations throughout the array. You need a position in each column; for this you can convert linear indices to indices with ind2sub
. Then the first element of the tuple index 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
I accepted the following function:
indmaxC(x) = cat(1, [indmax(x[:,c]) for c in 1:size(x,2)]...)
- The good: comfortable and small
- The bad: it is only valid for 2D arrays
More secure version:
function indmaxC(x::AbstractArray)
assert(ndims(x)==2)
cat(1, [indmax(x[:,c]) for c in 1:size(x,2)]...)
end