Almost, but not exactly. There are two steps involved in constructing a vector: (1) allocating space in memory and (2) actually setting that memory to some value. Vector{T}(undef, N)
tells Julia to only do step (1), which saves some time. That means that until you actually set each element of the vector, the data it contains is totally arbitrary and could be zeros or garbage or anything in between. Note how I get different contents each time I run this, based on whatever leftover data happened to be in memory:
julia> Vector{Float64}(undef, 2)
2-element Array{Float64,1}:
6.92131585940106e-310
0.0
julia> Vector{Float64}(undef, 2)
2-element Array{Float64,1}:
6.92131532920064e-310
6.9213154712449e-310
julia> Vector{Float64}(undef, 2)
2-element Array{Float64,1}:
5.0e-324
0.0
From this, you might be able to tell that there’s a bug in your code above. You are allocating an undef
vector for cor_vec
, but you’re only setting elements n:size(df)[1]
. That means that the first 1:(n-1)
elements will have garbage contents. To actually initialize those values to zero, you can do:
cor_vec = Vector{....
cor_vec .= 0 # fill with zeros
or
cor_vec = Vector{...
cor_vec .= missing # fill with missing
As a shortcut for the above, you can also just use zeros
as you did before:
julia> zeros(Union{Float64, Missing}, 5)
5-element Array{Union{Missing, Float64},1}:
0.0
0.0
0.0
0.0
0.0
As a further note, the undef
argument is new in Julia 0.7, but the behavior is not. Previously, Vector{T}(N)
did exactly what Vector{T}(undef, N)
does now, it was just less obvious. The undef
serves as a marker to be careful (and remember to actually set each element of the vector after you’ve constructed it), and also as a slot to put other kinds of initialization behaviors. For example, we can now do:
julia> Matrix{Float64}(undef, 2, 2)
2Ă—2 Array{Float64,2}:
6.92132e-310 6.92132e-310
6.92132e-310 0.0
to allocate a Matrix without setting its contents, or we can use I
instead of undef
to do:
julia> using LinearAlgebra
julia> Matrix{Float64}(I, 2, 2)
2Ă—2 Array{Float64,2}:
1.0 0.0
0.0 1.0
and create a Matrix and set its contents to be an identity matrix.