Iterating over and slicing a multidimensional array

You could try to use eachslice. It isn’t quite as elegant as you would hope but here goes:

julia> a = zeros(2,2);

julia> for (i, b) in enumerate(eachslice(a; dims=1))
           b .= i
       end

julia> a
2×2 Array{Float64,2}:
 1.0  1.0
 2.0  2.0

julia> for (i, b) in enumerate(eachslice(a; dims=2))
           b .= i
       end

julia> a
2×2 Array{Float64,2}:
 1.0  2.0
 1.0  2.0

Do you mind if i nitpick your code, btw? (I love nitpicking code, you see…)

Don’t do this:

for j in 1:2
    a[:,j] = j * ones(2)
end

On the right hand side here you allocate, not one, but two unnecessary temporary arrays. First, ones(2) allocates, and the multiplication with j allocates another array. Instead, just write

for j in 1:2
    a[:,j] .= j
end

No allocations! (Also, size(a)[dim] should be size(a, dim), which is a really tiny nit.)

4 Likes