Assign a value for one dimension of multi-dimensional array

I think a for loop is probably simplest for this.

julia> x = zeros(5,3,2);

julia> for k in axes(x,3)
               x[:,end,k] .= k
       end

julia> x
5×3×2 Array{Float64, 3}:
[:, :, 1] =
 0.0  0.0  1.0
 0.0  0.0  1.0
 0.0  0.0  1.0
 0.0  0.0  1.0
 0.0  0.0  1.0

[:, :, 2] =
 0.0  0.0  2.0
 0.0  0.0  2.0
 0.0  0.0  2.0
 0.0  0.0  2.0
 0.0  0.0  2.0

I don’t fully comprehend your last question, but you can achieve your last result using

julia> reduce(vcat,eachslice(x,dims=3))
10×3 Matrix{Float64}:
 0.0  0.0  1.0
 0.0  0.0  1.0
 0.0  0.0  1.0
 0.0  0.0  1.0
 0.0  0.0  1.0
 0.0  0.0  2.0
 0.0  0.0  2.0
 0.0  0.0  2.0
 0.0  0.0  2.0
 0.0  0.0  2.0

It seems like it might have been simpler to have used a 2-vector of 5x3 matrices to begin with. Unlike MATLAB, NumPy, and some other platforms, it isn’t necessary to vectorize operations to get fast code when using Julia.

You also could assemble your final matrix directly like

julia> y = zeros(10,3);

julia> for i in axes(y,1)
               y[i,end] = div(i-1,5)+1
       end

julia> y
10×3 Matrix{Float64}:
 0.0  0.0  1.0
 0.0  0.0  1.0
 0.0  0.0  1.0
 0.0  0.0  1.0
 0.0  0.0  1.0
 0.0  0.0  2.0
 0.0  0.0  2.0
 0.0  0.0  2.0
 0.0  0.0  2.0
 0.0  0.0  2.0
3 Likes