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.
In particular, julia arrays are stored in first-to-last dimension order (for matrices, "column-major" order), and hence you should nest iterations from last-to-first dimensions. For example, in the filtering example above we were careful to iterate in the order
But if by "recommended" what you really mean is "high-performance", then the best answer is: don't iterate over rows. The problem is that since arrays are stored in column-major order, for anything other than a small matrix you'll end up with a poor cache hit ratio if you traverse the array in row-major order.
Using sortslices () we can sort a multidimensional array in Julia. You supply a number or a tuple to the dims (“dimensions”) keyword that indicates what you want to sort. To sort the table so that the first column is sorted, use 1: Note that sortslices returns a new array.
As of Julia 1.1, there are iterator utilities for iterating over the columns or rows of a matrix. To iterate over rows: M = [1 2 3; 4 5 6; 7 8 9] for row in eachrow (af) println (row) end
for visibility: nowadays (julia > 1.1) use "eachrow"
for row in eachrow(A)
println(row)
end
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With