fill!
fill!(A, x)
Fill array A with the value x. If x is an object reference, all elements will refer to the same object. fill!(A, Foo()) will return A filled with the result of evaluating Foo() once.
Examples
julia> foo = Array(Int8,1,2);
julia> fill!(foo, 42)
1x2 Array{Int8,2}:
 42     42
Referencing another collection
 julia> foo = [1,2];
 julia> bar = Array(Any,1);
 julia> fill!(bar,foo)
 1-element Array{Any,1}:
  [1,2]
 julia> foo[1] = 42;
 julia> bar
 1-element Array{Any,1}:
 [42,2]
Using functions
julia> function Foo()
                    4^3
            end;
julia> bar = Array(Int8,2);
julia> fill!(bar, Foo())
2-element Array{Int64,1}:
 64
 64
- 
Fill an array with a specific value:
julia> arr = [0, 0, 0, 0, 0]; julia> fill!(arr, 5) 5-element Array{Int64,1}: 5 5 5 5 5This example fills the array
arrwith the value5. - 
Fill a matrix with a specific value:
julia> matrix = zeros(3, 3); julia> fill!(matrix, 1.5) 3×3 Array{Float64,2}: 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5It fills a matrix of zeros with the value
1.5. - 
Fill an array with a complex number:
julia> complex_arr = Vector{ComplexF64}(undef, 4); julia> fill!(complex_arr, 1 + 2im) 4-element Array{ComplexF64,1}: 1.0 + 2.0im 1.0 + 2.0im 1.0 + 2.0im 1.0 + 2.0imIn this example, it fills an array with complex numbers.
 - Fill an array with a custom object:
julia> struct Person name::String age::Int end julia> people = Vector{Person}(undef, 3); julia> fill!(people, Person("John", 25)) 3-element Array{Person,1}: Person("John", 25) Person("John", 25) Person("John", 25)The
fill!function can also be used to fill an array with custom objects. In this case, it fills an array with instances of thePersonstruct. 
Common mistake example:
julia> arr = [1, 2, 3, 4, 5];
julia> fill!(arr, 1:3)
ERROR: DimensionMismatch("tried to assign 3 elements to 5 destinations")
In this example, an error occurs because the size of the value being filled (1:3) does not match the size of the array (arr). Make sure the dimensions match to avoid such errors when using fill!.
See Also
Array, broadcast, cat, combinations, conj!, digits!, fieldnames, fill, fill!, last, length, maximum, minimum, ones, parent, parentindexes, partitions, permutations, pointer, pointer_to_array, promote_shape, rand!, reshape, scale, similar, sum, sum_kbn, takebuf_array, transpose!, vec, zeros,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.