Suppose I have a two dimensional array.
test_array = ones(2,2)
I can modify the last dimension of test_array by doing
test_array[:,1] = -99.
If I had test_array = ones(2,2,2),
I can do test_array[:,:,1] = - 99.
Suppose I want to write a function where I want to modify an array of arbitrary dimensions. For example, I could have test_array = ones([2 for i in 1:n]...) where n is arbitrary (e.g. an input for a function), and I want to modify the last dimension of test_array, how should I do it? Essentially I want to be able to put in an arbitrary number of :s when I do something analogous to test_array[:,:,1] = -99.
>Solution :
You can do e.g.:
julia> n = 4
4
julia> test_array = ones([2 for i in 1:n]...)
2×2×2×2 Array{Float64, 4}:
[:, :, 1, 1] =
1.0 1.0
1.0 1.0
[:, :, 2, 1] =
1.0 1.0
1.0 1.0
[:, :, 1, 2] =
1.0 1.0
1.0 1.0
[:, :, 2, 2] =
1.0 1.0
1.0 1.0
julia> test_array[fill(:, n-1)..., 1] .= -99
2×2×2 view(::Array{Float64, 4}, :, :, :, 1) with eltype Float64:
[:, :, 1] =
-99.0 -99.0
-99.0 -99.0
[:, :, 2] =
-99.0 -99.0
-99.0 -99.0
julia> test_array
2×2×2×2 Array{Float64, 4}:
[:, :, 1, 1] =
-99.0 -99.0
-99.0 -99.0
[:, :, 2, 1] =
-99.0 -99.0
-99.0 -99.0
[:, :, 1, 2] =
1.0 1.0
1.0 1.0
[:, :, 2, 2] =
1.0 1.0
1.0 1.0
or e.g.
julia> test_array = ones([2 for i in 1:n]...)
2×2×2×2 Array{Float64, 4}:
[:, :, 1, 1] =
1.0 1.0
1.0 1.0
[:, :, 2, 1] =
1.0 1.0
1.0 1.0
[:, :, 1, 2] =
1.0 1.0
1.0 1.0
[:, :, 2, 2] =
1.0 1.0
1.0 1.0
julia> first(eachslice(test_array, dims=n)) .= -99
2×2×2 view(::Array{Float64, 4}, :, :, :, 1) with eltype Float64:
[:, :, 1] =
-99.0 -99.0
-99.0 -99.0
[:, :, 2] =
-99.0 -99.0
-99.0 -99.0
julia> test_array
2×2×2×2 Array{Float64, 4}:
[:, :, 1, 1] =
-99.0 -99.0
-99.0 -99.0
[:, :, 2, 1] =
-99.0 -99.0
-99.0 -99.0
[:, :, 1, 2] =
1.0 1.0
1.0 1.0
[:, :, 2, 2] =
1.0 1.0
1.0 1.0