ones(A)

ones(A)

Create an array of all ones with the same element type and shape as A.

Examples

  1. Create a 1D array of ones:

    julia> ones(5)
    5-element Array{Float64,1}:
    1.0
    1.0
    1.0
    1.0
    1.0

    This example creates a 1-dimensional array of type Float64 with all elements set to 1.

  2. Create a 2D array of ones:

    julia> ones(Int, 3, 2)
    3×2 Array{Int64,2}:
    1  1
    1  1
    1  1

    It creates a 2-dimensional array of type Int64 with dimensions 3x2, where all elements are set to 1.

  3. Create a 3D array of ones:

    julia> ones(Float32, (2, 2, 2))
    2×2×2 Array{Float32,3}:
    [:, :, 1] =
    1.0  1.0
    1.0  1.0
    
    [:, :, 2] =
    1.0  1.0
    1.0  1.0

    This example generates a 3-dimensional array of type Float32 with dimensions 2x2x2, where all elements are set to 1.

Common mistake example:

julia> ones(5, 5, 5)
ERROR: MethodError: no method matching ones(::Int64, ::Int64, ::Int64)

In this example, the ones function is called with three integer arguments, expecting to create a 3-dimensional array. However, the correct syntax is to pass a type as the first argument and the dimensions as subsequent arguments or as a tuple.

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: