Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: how to iterate row by row in a multidimensional array

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.

like image 862
Pigna Avatar asked Oct 30 '17 16:10

Pigna


People also ask

What order should I iterate through Julia arrays in?

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

Is it recommended to iterate over rows in an array?

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.

How do you sort a multidimensional array in Julia?

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.

How do you iterate over a matrix in Julia?

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


2 Answers

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

for row in eachrow(A)
    println(row)
end
like image 65
guest3457823 Avatar answered Oct 19 '22 15:10

guest3457823


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.

like image 27
Chris Rackauckas Avatar answered Oct 19 '22 16:10

Chris Rackauckas