Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over whole array when I need i, j, k?

Tags:

julia

Given A is a multi-dimensional array, can I collapse iteration through every element into one for statement if I need i,j,k,etc.? In other words, I am looking for a more compact version of the following:

for k in 1:size(A,3)
  for j in 1:size(A,2)
    for i in 1:size(A,1)
      # Do something with A[i+1,j,k], A[i,j+1,k], A[i,j,k+1], etc.
    end
  end
end

I think the solution is with axes or CartesianIndices, but I can't get the syntax right. Failed attempts:

julia> for (i,j,k) in axes(A)
         println(i)
       end
1
1
1

julia> for (i,j,k) in CartesianIndices(A)
           println(i)
       end
ERROR: iteration is deliberately unsupported for CartesianIndex. Use `I` rather than `I...`, or use `Tuple(I)...`

It would be great if in addition to a solution which defines i,j,k, you could also provide a solution that works regardless of the number of dimensions in A.

like image 388
Nathan Boyer Avatar asked Oct 31 '25 14:10

Nathan Boyer


1 Answers

You are almost there. Read the message carefully:

ERROR: iteration is deliberately unsupported for CartesianIndex.

It is the "pattern matching" in (i,j,k) in CartesianIndices(...) that fails, not the approach in general (I made the same mistake when reproducing the problem!). You have to convert the individual CartesianIndexes to tuples first:

julia> for ix in CartesianIndices(A)
           println(Tuple(ix))
       end
(1, 1, 1)
(2, 1, 1)
(3, 1, 1)
(1, 2, 1)
(2, 2, 1)
(3, 2, 1)
...
like image 153
phipsgabler Avatar answered Nov 02 '25 13:11

phipsgabler



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!