Search code examples
arraysinitializationjulia

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


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])

Solution

  • 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)