fill

fill(x, dims)

Create an array filled with the value x. For example, fill(1.0, (10,10)) returns a 10x10 array of floats, with each element initialized to 1.0.

If x is an object reference, all elements will refer to the same object. fill(Foo(), dims) will return an array filled with the result of evaluating Foo() once.

Examples

julia> fill(3, 1)
1-element Array{Int64,1}:
 3

Referencing another collection

 julia> foo = [1,2];
 julia> bar = fill(foo, 1, 2)
 1x2 Array{Array{Int64,1},2}:
  [1,2]     [1,2]
 julia> foo[1] = 42;
 julia> bar
 1x2 Array{Array{Int64,1},2}:
 [42,2]     [42,2]

Using functions

julia> function Foo()
                    4^3
            end;
julia> fill(Foo(), 1)
1-element Array{Int64,1}:
 64
  1. Fill an array with a specific value:

    julia> fill(0, (3, 3))
    3×3 Array{Int64,2}:
    0  0  0
    0  0  0
    0  0  0

    This example creates a 3x3 array filled with the value 0.

  2. Fill an array with a float value:

    julia> fill(1.5, (2, 4))
    2×4 Array{Float64,2}:
    1.5  1.5  1.5  1.5
    1.5  1.5  1.5  1.5

    It generates a 2x4 array filled with the float value 1.5.

  3. Fill an array with a custom object:

    julia> struct Person
              name::String
              age::Int
          end
    
    julia> fill(Person("John", 30), (2, 2))
    2×2 Array{Person,2}:
    Person("John", 30)  Person("John", 30)
    Person("John", 30)  Person("John", 30)

    In this example, we create a custom Person object and fill a 2x2 array with the same object reference.

  4. Fill a 1-dimensional array with a specific value:
    julia> fill("Hello", 5)
    5-element Array{String,1}:
    "Hello"
    "Hello"
    "Hello"
    "Hello"
    "Hello"

    It creates a 1-dimensional array of length 5, with each element initialized to the string "Hello".

Common mistake example:

julia> fill(2, -1)
ERROR: DimensionMismatch("dims and val must have the same length")

In this example, the dimensions provided are not compatible with the value 2. Make sure that the dimensions and value have compatible lengths to avoid this error.

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.

*Required Field
Details

Checking you are not a robot: