Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modify the last dimension of a multi-dimensional array of arbitrary dimensions

Suppose I have a two dimensional array.

test_array = ones(2,2)

I can modify the last dimension of test_array by doing

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading