# \[Julia usage\] How to get 2D indexes from 1D index when accessing a 2D array?

**URL:** <https://discourse.julialang.org/t/julia-usage-how-to-get-2d-indexes-from-1d-index-when-accessing-a-2d-array/61440>\
**Category:** New to Julia\
**Tags:** indexing, array\
**Created:** [May 19, 2021, 1:11pm UTC](https://discourse.julialang.org/t/julia-usage-how-to-get-2d-indexes-from-1d-index-when-accessing-a-2d-array/61440 "2021-05-19T13:11:07Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![erwanlecarpentier](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/erwanlecarpentier/32/23448_2.png) [@erwanlecarpentier](https://discourse.julialang.org/u/erwanlecarpentier)\
**Post date:** [May 19, 2021, 1:11pm UTC](https://discourse.julialang.org/t/julia-usage-how-to-get-2d-indexes-from-1d-index-when-accessing-a-2d-array/61440/1 "2021-05-19T13:11:07Z")

</div>

Hi! I have a 2D array `x`. I can access its elements by using “1D indexing” (e.g. `x[3]`) or “2D indexing” (e.g. `x[3, 1]`).  
**Question:** given an integer `i` that could be used as a 1D index, how to retrieve the 2D indexes `r, c` that would access the same element of `x` (i.e. `x[i] == x[r, c]` is true)?

Here is a function that does what I am looking for using `divrem`, though I wonder if there exists built-in functions or more elegant alternatives.

```julia
function index1d_to_index2d(x::AbstractArray, index::Int64)::Tuple{Int64,Int64}
    n_rows = size(x)[1]
    q, r = divrem(index, n_rows)
    if r == 0
        return n_rows, q
    else
        return r, q + 1
    end
end

```

Test code:

```julia
x = rand(7, 10)
for i in 1:length(x)
    r, c = index1d_to_index2d(x, i)
    @assert x[i] == x[r, c]
end

```

Thanks!

---

<div class="post-metadata">

**Author:** ![fedoroff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fedoroff/32/53209_2.png) [@fedoroff](https://discourse.julialang.org/u/fedoroff)\
**Post date:** [May 19, 2021, 1:24pm UTC](https://discourse.julialang.org/t/julia-usage-how-to-get-2d-indexes-from-1d-index-when-accessing-a-2d-array/61440/2 "2021-05-19T13:24:55Z")

</div>

Take a look at CartesianIndices:

```julia
x = rand((7, 10))
CI = CartesianIndices((7, 10))
for i in 1:length(x)
    r = CI[i][1]
    c = CI[i][2]
    @assert x[i] == x[r, c]
end

```

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [May 19, 2021, 2:01pm UTC](https://discourse.julialang.org/t/julia-usage-how-to-get-2d-indexes-from-1d-index-when-accessing-a-2d-array/61440/3 "2021-05-19T14:01:55Z")

</div>

Is there a way to use `CartesianIndices` while avoiding the allocation of the array of indices?

---

<div class="post-metadata">

**Author:** ![fedoroff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fedoroff/32/53209_2.png) [@fedoroff](https://discourse.julialang.org/u/fedoroff)\
**Post date:** [May 19, 2021, 2:14pm UTC](https://discourse.julialang.org/t/julia-usage-how-to-get-2d-indexes-from-1d-index-when-accessing-a-2d-array/61440/4 "2021-05-19T14:14:23Z")

</div>

This is the non-allocating operation (no array of indices is created):

```julia
using BenchmarkTools

@btime CI = CartesianIndices((7, 10))

0.018 ns (0 allocations: 0 bytes)

```

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [May 19, 2021, 2:18pm UTC](https://discourse.julialang.org/t/julia-usage-how-to-get-2d-indexes-from-1d-index-when-accessing-a-2d-array/61440/5 "2021-05-19T14:18:59Z")

</div>

Interesting. Seems miraculous to me 🙂

Just a more comprehensive test:

```julia
julia> function mutx!(x)
         CI = CartesianIndices(size(x))
         for i in eachindex(x)
           r = CI[i][1]
           c = CI[i][2]
           x[r,c] += 1 
         end
       end
mutx! (generic function with 1 method)

julia> @btime mutx!(x) setup=(x=zeros(10,10))
  332.971 ns (0 allocations: 0 bytes)

```

That is slower than running over the indexes directly, though:

```julia
julia> function mutx2!(x)
         for j in 1:size(x,2)
           for i in 1:size(x,1)
             x[i,j] += 1 
           end
         end
       end
mutx2! (generic function with 1 method)

julia> @btime mutx2!(x) setup=(x=zeros(10,10))
  51.810 ns (0 allocations: 0 bytes)

```

(probably that doesn’t matter for loops doing something more meaningful at each iteration, but maybe someone has something to comment on this).

---

<div class="post-metadata">

**Author:** ![aramirezreyes](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/aramirezreyes/32/42573_2.png) [@aramirezreyes](https://discourse.julialang.org/u/aramirezreyes)\
**Post date:** [May 19, 2021, 4:30pm UTC](https://discourse.julialang.org/t/julia-usage-how-to-get-2d-indexes-from-1d-index-when-accessing-a-2d-array/61440/6 "2021-05-19T16:30:42Z")

</div>

Interesting

```julia
julia> function mutx!(x)
                CI = CartesianIndices(size(x))
                for i in eachindex(x)
                  r = CI[i][1]
                  c = CI[i][2]
                  x[r,c] += 1
                end
              end
mutx! (generic function with 1 method)

julia> function mutx2!(x)
                for j in 1:size(x,2)
                  for i in 1:size(x,1)
                    x[i,j] += 1
                  end
                end
              end
mutx2! (generic function with 1 method)

julia> function mutx3!(x)
                for i in CartesianIndices(x)
                  x[i] += 1
                end
              end
mutx3! (generic function with 1 method)

julia> function mutx4!(x)
                CI = CartesianIndices(size(x))
                       for i in CI
                           x[i] += 1
                       end
                     end
mutx4! (generic function with 1 method)

julia> @btime mutx!(x) setup=(x=zeros(10,10))
  276.409 ns (0 allocations: 0 bytes)

julia> @btime mutx2!(x) setup=(x=zeros(10,10))
  45.005 ns (0 allocations: 0 bytes)

julia> @btime mutx3!(x) setup=(x=zeros(10,10))
  42.740 ns (0 allocations: 0 bytes)

julia> @btime mutx4!(x) setup=(x=zeros(10,10))
  42.757 ns (0 allocations: 0 bytes)

```

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [May 19, 2021, 5:16pm UTC](https://discourse.julialang.org/t/julia-usage-how-to-get-2d-indexes-from-1d-index-when-accessing-a-2d-array/61440/7 "2021-05-19T17:16:34Z")

</div>

one more for the list:

```julia
julia> function mutx!(x)
                for pair in CartesianIndices(x)
                  i = pair[1]
                  j = pair[2]
                  x[i,j] += 1
                end
              end
mutx! (generic function with 1 method)

julia> @btime mutx!(x) setup=(x=zeros(10,10))
  47.928 ns (0 allocations: 0 bytes)

```

the slowness comes from _not_ iterating over the `CartesianIndexes`.

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [May 19, 2021, 6:01pm UTC](https://discourse.julialang.org/t/julia-usage-how-to-get-2d-indexes-from-1d-index-when-accessing-a-2d-array/61440/8 "2021-05-19T18:01:14Z")

</div>

Probably because _indexing_ into a `CartesianIndices` requires a division operation, while _iterating over_ one does not, right?

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [May 19, 2021, 6:16pm UTC](https://discourse.julialang.org/t/julia-usage-how-to-get-2d-indexes-from-1d-index-when-accessing-a-2d-array/61440/9 "2021-05-19T18:16:34Z")

</div>

Probably. I guess that overhead will always exist if one tries to iterate over indices that do not comprise necessarily _all_ Cartesian indices, thus having to actually compute the indices (and then the miracle I was referring to starts to make sense).

The fact that the overhead exists if one iterates over `eachindex(x)` is something that could possibly be solved by a compiler optimization, but it does not.
