# Argmax over columns of a large matrix

**URL:** https://discourse.julialang.org/t/argmax-over-columns-of-a-large-matrix/121924
**Category:** Performance
**Tags:** matrix
**Created:** [October 29, 2024, 3:24pm UTC](https://discourse.julialang.org/t/argmax-over-columns-of-a-large-matrix/121924 "2024-10-29T15:24:21Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![miguelborrero](https://avatars.discourse-cdn.com/v4/letter/m/eb9ed0/32.png) [@miguelborrero](https://discourse.julialang.org/u/miguelborrero)
#### Post date: [October 29, 2024, 3:24pm UTC](https://discourse.julialang.org/t/argmax-over-columns-of-a-large-matrix/121924/1 "2024-10-29T15:24:21Z")

</div>

Hi there,

I have a large matrix for e.g (7x10000) and I want to iterate over each of the columns and compute the index of the maximum element. There are naive ways I can think of but since this part of my code is performance critical I wanted to ask more experienced users what would be the most efficient approach to do so?

Thanks a lot in advance!

---

<div class="post-metadata">

### Author: ![mikmoore](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikmoore/32/31109_2.png) [@mikmoore](https://discourse.julialang.org/u/mikmoore)
#### Post date: [October 29, 2024, 4:21pm UTC](https://discourse.julialang.org/t/argmax-over-columns-of-a-large-matrix/121924/2 "2024-10-29T16:21:47Z")

</div>

I’d keep it simple with the builtin `argmax`. There are two ways I would try, the dimensional `argmax` and map/broadcast over `eachcol`.

```julia-repl
julia> argmax(rand(7,5); dims=1)
1×5 Matrix{CartesianIndex{2}}:
 CartesianIndex(6, 1) CartesianIndex(2, 2) CartesianIndex(2, 3) CartesianIndex(3, 4) CartesianIndex(7, 5)

julia> map(argmax, eachcol(rand(7,5)))
5-element Vector{Int64}:
 4
 7
 6
 3
 3

```

When I benchmark these on your 7x10000 matrix, I find the `map` solution to be faster.

Although [`argmin()` is much slower than `findmin()` due to automatic inline · Issue #56375 · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/issues/56375) suggests that `argmax` might be slower than necessary at present, I expect that will be fixed soon™ so would prefer to stick to builtins. In a few minutes of trying, I couldn’t write a version that was faster for your length=7 columns anyway, so that issue might be irrelevant at this size.

---

<div class="post-metadata">

### Author: ![miguelborrero](https://avatars.discourse-cdn.com/v4/letter/m/eb9ed0/32.png) [@miguelborrero](https://discourse.julialang.org/u/miguelborrero)
#### Post date: [October 29, 2024, 6:50pm UTC](https://discourse.julialang.org/t/argmax-over-columns-of-a-large-matrix/121924/3 "2024-10-29T18:50:52Z")

</div>

Thanks a lot!
