7

Say that I have 4x4 multidimensional array A:

A = collect(reshape(1:16, 4, 4))
4×4 Array{Int64,2}:
 1  5   9  13
 2  6  10  14
 3  7  11  15
 4  8  12  16

and I want to iterate row by row (i.e. [1, 5, 9, 13] first, then [2, 6, 10, 14], then ...).

How do I do it? For now I have come up with the following:

`for row in 1:size(A, 1)
    println(A[row, :])
    # do something
end`

but I was wondering if there was a more "pythonic" way of doing it: kind of for line in A: for element in line: ....

I also know about CartesianRange, but I would like to have an array-like row to work with at each iteration.

4
  • 1
    This question may be relevant: stackoverflow.com/questions/21778374/… Commented Oct 30, 2017 at 16:49
  • 1
    Possible duplicate of What is the recommended way to iterate a matrix over rows? Commented Oct 30, 2017 at 16:53
  • 1
    Your PS isn't a dumb question at all — I'd split it out and ask it independently of the iterate-by-rows question. Commented Oct 30, 2017 at 16:54
  • I will do that. Thanks, I am going to close this question Commented Oct 30, 2017 at 16:57

3 Answers 3

11

for visibility: nowadays (julia > 1.1) use "eachrow"

for row in eachrow(A)
    println(row)
end
Sign up to request clarification or add additional context in comments.

Comments

1

Because arrays in Julia are stored column-major, it may be wiser / more performant to just transpose the matrix (A') and then iterate through it if you want to do a lot of things row-by-row.

4 Comments

Ok, but once it is transposed how do i get the behavior I want? I looked in to the suggested duplicate and the only way is through slicing. I don't get the "line" as in Python
Once you made the column-major matrix, you might as well use views.
Here are two issues asking for a function rows to enable for row in rows(A) github.com/JuliaLang/julia/issues/14491 and github.com/JuliaCollections/IterTools.jl/issues/11
Maybe A.' is better answer. Currently nor A' nor A.' support structural transpose and something like permutedims(A, (2,1)) is necessary if A is for example array of strings. See: github.com/JuliaLang/julia/issues/20978 (there is chance that A.' will do structural transpose in Julia 1.0)
1

A very nice package for this kind of thing is JuliennedArrays.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.