# Find the maximum for each position of a set of arrays

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]
``````

`[maximum.(b) for b in eachrow(a)]`

1 Like

It gives me the maximum of each elemt. I would like the maximimum by position, for each row.

1 Like

Here are two ways:

``````julia> a = [  [[8, 13, 1]]   [[12, 4, 9]]  [[13, 18, 7]]
[[3, 19, 20]]  [[8, 3, 11]]  [[10, 9, 12]]  ]  # as in original question
2×3 Matrix{Vector{Int64}}:
[8, 13, 1]   [12, 4, 9]  [13, 18, 7]
[3, 19, 20]  [8, 3, 11]  [10, 9, 12]

julia> [maximum.(b) for b in eachrow(a)]  # answer above
2-element Vector{Vector{Int64}}:
[13, 12, 18]
[20, 11, 12]

julia> map(eachrow(a)) do row  # desired result
max.(row...)
end
2-element Vector{Vector{Int64}}:
[13, 18, 9]
[10, 19, 20]

julia> using TensorCast

julia> @reduce _[i][k] := maximum(j) a[i,j][k]
2-element Vector{SubArray{Int64, 1, Matrix{Int64}, Tuple{Base.Slice{Base.OneTo{Int64}}, Int64}, true}}:
[13, 18, 9]
[10, 19, 20]
``````

But note that it’s normally easier to work with one 3D-array, instead of arrays of arrays. (This is what `@reduce` is doing, it concatenates, takes `maximum(tmp, dims = 3)`, then slices again.)

3 Likes

Thanks for the answer. If you wish, you can also answer the same question on the stackoverflow:
In Julia, Find the maximum for each position of a set of arrays - Stack Overflow
I’ll give you the ok on this platform too.

Ok, this one-liner comprehension seems to do the job:
`[maximum(hcat(b...),dims=2) for b in eachrow(a)]`

1 Like