# Performance tips for a function which finds n maximums in a matrix

**URL:** https://discourse.julialang.org/t/performance-tips-for-a-function-which-finds-n-maximums-in-a-matrix/96425
**Category:** Performance
**Tags:** performance, sortperm, speed-optimization, matrix
**Created:** [March 22, 2023, 12:19am UTC](https://discourse.julialang.org/t/performance-tips-for-a-function-which-finds-n-maximums-in-a-matrix/96425 "2023-03-22T00:19:59Z")
**Posts on this page:** 1
**Showing post:** 4

<div class="post-metadata">

### Author: ![JM\_Beckers](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jm_beckers/32/22482_2.png) [@JM\_Beckers](https://discourse.julialang.org/u/JM_Beckers)
#### Post date: [March 22, 2023, 5:45am UTC](https://discourse.julialang.org/t/performance-tips-for-a-function-which-finds-n-maximums-in-a-matrix/96425/4 "2023-03-22T05:45:30Z")

</div>

Or you adapt this one to get the maxima instead of minima, which is very efficient for small n.

> [@Find n smallest values in an n dims array](https://discourse.julialang.org/t/find-n-smallest-values-in-an-n-dims-array/81092/13):
>
> I think this version is not optimal if n is very small compared to the size of the array since you make a full sort and just retain a few smallest values. At the limit, imagine to get the lowest value of an array you make a sort first. That does not sound right. A dirty write-up like the following using BenchmarkTools A=rand(100,100,10,40,10); function arg\_n\_smallest\_values(A::AbstractArray{T,N}, n::Integer) where {T,N} perm = sortperm(vec(A)) ci = CartesianIndices(A) …

---

_[View the full topic](https://discourse.julialang.org/t/performance-tips-for-a-function-which-finds-n-maximums-in-a-matrix/96425)._
