Iterating array like numpy?

Julia seems broadcast/iterate array by elements:

arr = zeros(Float32, 3, 2)
for x in arr
println(x)
end
# output 6 lines of 0.0

I’m wondering if we can iterate normal arrays like numpy fashion, thus can we have:

arr = zeros(Float32, 3, 2)
for x in arr # or something others
println(x)
end
# output 3 lines of (0.0, 0.0)

I noticed that

arr = [[1,2],[3,4]]
for x in arr
println(x)
end

will produce

[1,2]
[3,4]

but type of arr here is Array{Array{Int64,1},1}, not Array{Int64, 2}, and can not select element by arr[1,2].

As an summary, can we broadcast only on first dimension(or a specified dimension/axis) of an array?

1 Like

Does this help?

julia> A = rand(1:10, 3, 2)
3×2 Array{Int64,2}:
 2  9
 1  8
 3  3

julia> for rowindex in axes(A, 1)
       @show A[rowindex, :]
       end
A[rowindex, :] = [2, 9]
A[rowindex, :] = [1, 8]
A[rowindex, :] = [3, 3]

You can use a @view to speed things up in some cases (benchmark!).

If you need an actual iterable for the rows (or their views), that is also easy, just ask.

2 Likes