JuliaLang / julia

The Julia Programming Language
https://julialang.org/
MIT License
45.69k stars 5.48k forks source link

More iteration documentation explanations. #44540

Open nathanrboyer opened 2 years ago

nathanrboyer commented 2 years ago

https://docs.julialang.org/en/v1/manual/arrays/#Iteration The documentation here needs a section on iterating over slices of an array.

My first instinct coming from Matlab is to write loops like this:

for i in 1:length(A[:,1])
end

If I come across size elsewhere in the documentation, then I might switch to the better:

for i in 1:size(A,1)
end

However, neither of the above should really be used. pairs and axes are usually suggested on Discourse instead, but these function names are not intuitive to search for or use in this context. It would be nice to explain when to use the many different indexing functions available in Julia and their interaction with CartesianIndices.

Another topic that should be addressed in this section is the correct syntax order for accessing arrays in column order. In the examples below, the loop order of nested! and comprehension are natural to me, but the loop order of nested_compact! seems backwards. Since it is not obvious how the loops unwrap, it should be documented.

function nested!(A)
    for k in axes(A,3) 
       for j in axes(A,2) 
           for i in axes(A,1)
              A[i,j,k] = A[i,j,k] - 1.0
           end
       end
    end
 end

function nested_compact!(A)
    for k in axes(A,3), j in axes(A,2), i in axes(A,1)
        A[i,j,k] = A[i,j,k] - 1.0
    end
end

function comprehension(A)
    B = [A[i,j,k] + 1.0 for i in axes(A,1), j in axes(A,2), k in axes(A,3)]
end
timholy commented 2 years ago

Care to submit a pull request? You can just click "Fork" and hit "." to open a browser instance of VSCode.

nathanrboyer commented 2 years ago

Hopefully someday. I have DataFrames documentation that I need to finish first, and I still don't totally understand how pairs and CartesianIndices are supposed to be used.