# Find n smallest values in an n dims array

**URL:** https://discourse.julialang.org/t/find-n-smallest-values-in-an-n-dims-array/81092
**Category:** New to Julia
**Tags:** question, sort, sortperm, arrays, cartesianindices
**Created:** [May 15, 2022, 12:07pm UTC](https://discourse.julialang.org/t/find-n-smallest-values-in-an-n-dims-array/81092 "2022-05-15T12:07:22Z")
**Posts on this page:** 1
**Showing post:** 9

<div class="post-metadata">

### Author: ![mkitti](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mkitti/32/12459_2.png) [@mkitti](https://discourse.julialang.org/u/mkitti)
#### Post date: [May 15, 2022, 5:57pm UTC](https://discourse.julialang.org/t/find-n-smallest-values-in-an-n-dims-array/81092/9 "2022-05-15T17:57:23Z")

</div>

> [@JeffreySarnoff](#):
>
> ```julia
> indexmins(M, n) = 
> CartesianIndices(M)[
> sort(findall(x->(x <= n), 
> sortperm(vec(M))))]
> 
> ```

@JeffreySarnoff that seems to do something different than how I interpreted the question.

```julia
julia> A = rand(0:128, 4, 3, 2)
4×3×2 Array{Int64, 3}:
[:, :, 1] =
 33 83 7
 41 128 107
 86 3 17
 64 115 25

[:, :, 2] =
 61 46 81
 23 75 92
 58 58 40
 24 103 20

julia> indexmins(M, n) =
              CartesianIndices(M)[
                        sort(findall(x->(x <= n),
                             sortperm(vec(M))))]
indexmins (generic function with 1 method)

julia> ind = indexmins(A, 5)
5-element Vector{CartesianIndex{3}}:
 CartesianIndex(4, 2, 1)
 CartesianIndex(2, 3, 1)
 CartesianIndex(3, 1, 2)
 CartesianIndex(2, 2, 2)
 CartesianIndex(3, 2, 2)

julia> A[ind]
5-element Vector{Int64}:
 115
 107
  58
  75
  58

```

I thought he wanted the indices of the 5 smallest values in the original array:

```julia
julia> function arg_n_smallest_values(A::AbstractArray{T,N}, n::Integer) where {T,N}
           perm = sortperm(vec(A))
           ci = CartesianIndices(A)
           return ci[perm[1:n]]
       end
arg_n_smallest_values (generic function with 2 methods)

julia> ind = arg_n_smallest_values(A, 5)
5-element Vector{CartesianIndex{3}}:
 CartesianIndex(3, 2, 1)
 CartesianIndex(1, 3, 1)
 CartesianIndex(3, 3, 1)
 CartesianIndex(4, 3, 2)
 CartesianIndex(2, 1, 2)

julia> A[ind]
5-element Vector{Int64}:
  3
  7
 17
 20
 23

```

---

_[View the full topic](https://discourse.julialang.org/t/find-n-smallest-values-in-an-n-dims-array/81092)._
