'In JULIA how do I preallocate a Measurements.jl vector with n rows?

I want to preallocate a vector with n rows (e.g. A below) ready for filling in a loop with Measurements.jl variables, i.e. variables of the form a ± b. For example:

using Measurements
A = zeros(5,1) # this doesn't work
for n = 1:5
  local B = rand() ± rand()
  local C = rand() ± rand()
  global A[n,1] = sqrt.((B-C).^2)
end
println(A)


Solution 1:[1]

You can make an array of Measurements.jl Measurements is several ways, including

A = fill(0±0, size)

or

A = Array{Measurement}(undef, size)

For example

using Measurements
A = fill(0±0, 5, 1)
for n = 1:5
  B = rand() ± rand()
  C = rand() ± rand()
  A[n,1] = sqrt.((B-C).^2)
end
julia> A
5×1 Matrix{Measurement{Float64}}:
 0.28 ± 1.0
 0.45 ± 0.87
 0.67 ± 0.58
 0.28 ± 0.62
  0.3 ± 0.67

N.B., you shouldn't generally need those global and local annotations here, unless you're running in global scope in a script (as opposed to in a REPL, in a function, a let block, or really anywhere else).

Solution 2:[2]

We can also provide a type for the function zeros. If we execute the follwing code.

using Measurements
A = zeros(Measurement,5,1) # provide the type Measurement here
for n = 1:5
  local B = rand() ± rand()
  local C = rand() ± rand()
  global A[n,1] = sqrt.((B-C).^2)
end

yields to

5×1 Matrix{Measurement}:
 0.068 ± 1.1
  0.63 ± 0.95
  0.88 ± 0.43
  0.73 ± 0.17
 0.069 ± 0.95

We can also be more strict if we provide the types inside the measurements by providing using A = zeros(Measurement{Float64},5,1) which yields a 5×1 Matrix{Measurement{Float64}}.

It also works if we provide the type Real yielding in a 5x1 Matrix of type Real.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cbk
Solution 2 David Scholz