I would like to create an array with the value of 430, which repeats 5 times, so the output would look approximately like (this is simulated output):
julia> CC
5-element Array{Float64,1}:
430.0
430.0
430.0
430.0
430.0
I have tried using the example from here which looks like this
array = Array{Int64}(undef, 5)
and then specifying
CC = Array{Float64}(430.0, 5)
But this of course generates an error
ERROR: MethodError: no method matching Array{Float64,N} where N(::Float64, ::Int64)
Closest candidates are:
Array{Float64,N} where N(::UndefInitializer, ::Int64) where T at boot.jl:408
Array{Float64,N} where N(::UndefInitializer, ::Int64, ::Int64) where T at boot.jl:409
Array{Float64,N} where N(::UndefInitializer, ::Int64, ::Int64, ::Int64) where T at boot.jl:410
...
Stacktrace:
[1] top-level scope at none:0
Could someone please show me the correct way to do this?
It would be good to follow this up with a reason. Being MATLAB-ish is not a good reason
The ones solution creates a vector with the values 1.0, then multiplies each entry with 430, storing the result in a new array in the process. This is both slower and allocates more memory than the fill solution, and is clearly inferior in terms of performance.
However, for small sporadic arrays, or working in the REPL, this doesn’t really matter, and it is in fact the shortest way I know of to solve the problem, which makes it more convenient to type in the REPL
From a language-learning perspective, I also think it’s interesting to see different ways to solve a problem. Here are a few more, all approximately as efficient as fill for larger vectors, not as readable, but interesting nonetheless IMO:
1:5 .|>_-> 430.0
(_->430.0).(1:5)
[430.0 for _=1:5]
map(_->430.0, 1:5)