Julia Quick way to initialise an empty array that's the same size as another?

Viewed 1356

I have an array

array1 = Array{Int,2}(undef, 2, 3)

Is there a way to quickly make a new array that's the same size as the first one? E.g. something like

array2 = Array{Int,2}(undef, size(array1))

current I have to do this which is pretty cumbersome, and even worse for higher dimension arrays

array2 = Array{Int,2}(undef, size(array1)[1], size(array1)[2])
2 Answers

What you're looking for is similar(array1).

You can even change up the array type by passing in a type, e.g.

similar(array1, Float64)
similar(array1, Int64)

Using similar is a great solution. But the reason your original attempt doesn't work is the number 2 in the type parameter signature: Array{Int, 2}. The number 2 specifies that the array must have 2 dimensions. If you remove it you can have exactly as many dimensions as you like:

julia> a = rand(2,4,3,2);

julia> b = Array{Int}(undef, size(a));

julia> size(b)
(2, 4, 3, 2)

This works for other array constructors too:

zeros(size(a))
ones(size(a))
fill(5, size(a))
# etc.
Related