Array with constant values

I wish to create an array whose length is 102 and having constant values everywhere without defining a for-loop explicitly. Assuming such an array ArrayWithConst, if I define it like ArrayWithConst[1:end]=5.0, this generates an error. I wonder how to implement this. Thanks in advance for kind advices.

fill(5.0, 102)

Is this what you are looking for?

6 Likes

Also, your code is almost right. If you already have ArrayWithConst, then setting all of its values to 5.0 can be done by ArrayWithConst[1:end] .= 5.0 (note the dot before the =).

2 Likes

thanks!

thanks. this does not work for me (type mismatch error). I first defined xd=1.5:0.05:6.55, then ArrayWithConstant=copy(xd) for preparation.

You need a mutable copy, not a range (which is returned by copy of a range). Try Vector(xd) instead of copy(xd), for example (or Base.copymutable(xd)).

(But better yet, just do fill(5.0, length(xd)) — it is pointless to make a copy just to overwrite it.)

2 Likes

Why not the basic: ArrayWithConst = zeros(102) .+ 5.0 ?

That’s almost certainly 2x slower (with not much gain).

4 Likes