In Julia, Find the maximum for each position of a set of arrays

Viewed 251

I have an array like this

a = [ rand(1:20,3)  for i in 1:2,j in 1:3]
2×3 Array{Array{Int64,1},2}:
2×3 Array{Array{Int64,1},2}:
 [8, 13, 1]   [12, 4, 9]  [13, 18, 7]
 [3, 19, 20]  [8, 3, 11]  [10, 9, 12]

I would like that for each row, obtain an array 1 x 3 with maximum in each position along the row. For example, in the example above:

[13,18,9]
[10,19,20]

(this question was also asked on another platform: https://discourse.julialang.org/t/find-the-maximum-for-each-position-of-a-set-of-arrays/62155/3 )

2 Answers

If I understand your question right you can just vectorize over maximum:

julia> a = [ rand(1:20,3)  for i in 1:2,j in 1:3]
2×3 Matrix{Vector{Int64}}:
 [13, 10, 10]  [14, 8, 9]    [15, 8, 5]
 [18, 18, 7]   [19, 10, 17]  [17, 8, 7]

julia> maximum.(a)
2×3 Matrix{Int64}:
 13  14  15
 18  19  17

Should you want to have a vector of rows use collect combined with eachrow:

julia> collect(eachrow(maximum.(a)))
2-element Vector{SubArray{Int64, 1, Matrix{Int64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}}:
 [13, 14, 15]
 [18, 19, 17]

Answers from the linked Discourse thread:

julia> a = [  [[8, 13, 1]]   [[12, 4, 9]]  [[13, 18, 7]]
        [[3, 19, 20]]  [[8, 3, 11]]  [[10, 9, 12]]  ];  # as in question

julia> res1 = [max.(row...) for row in eachrow(a)]
2-element Vector{Vector{Int64}}:
 [13, 18, 9]
 [10, 19, 20]

julia> res1 == [vec(maximum(reduce(hcat, row), dims=2)) for row in eachrow(a)]
true

julia> using TensorCast

julia> res1 == @reduce res[i][k] := maximum(j) a[i,j][k]
true

Compare:

julia> res2 = collect.(eachrow(maximum.(a)))
2-element Vector{Vector{Int64}}:
 [13, 12, 18]
 [20, 11, 12]

julia> res2 == [maximum.(b) for b in eachrow(a)]
true

julia> res2 == @reduce res[i][j] := maximum(k) a[i,j][k]
true
Related