Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: Is there a way to return an iterator of each value of an index?

Tags:

julia

Consider m = [1 2 3; 4 5 6; 7 8 9]

for idx in eachindex(m)
  println(idx)
end

I was expecting it to print (1, 1) (2, 1), (3, 1) .... (1, 3), (2, 3), (3, 3) but it prints 1, 2, ..., 9.

What's the most elegant way to loop through all the indices of a multidimensional array?

like image 637
xiaodai Avatar asked Sep 06 '25 03:09

xiaodai


1 Answers

What about

julia> for i in CartesianIndices(m)
           println(Tuple(i))
       end
(1, 1)
(2, 1)
(3, 1)
(1, 2)
(2, 2)
(3, 2)
(1, 3)
(2, 3)
(3, 3)

(You can access the tuple of subindices of i::CartseianIndex with Tuple(i).)

like image 136
Benoit Pasquier Avatar answered Sep 07 '25 23:09

Benoit Pasquier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!