Julia Creating Arrays
Builder functions create an array of a chosen size without typing every value. Each builder fills the new array in its own simple way.
zeros and ones fill with fixed values
The number in the call sets the size. Both builders fill with decimal values.
println(zeros(3))
println(ones(2))fill repeats a value and collect builds from a range
fill repeats one value to a chosen size. collect turns a range, even a stepped one, into an array.
println(fill(7, 3))
println(collect(1:4))
println(collect(2:2:8))An empty typed array can grow with push!
Int[] makes an empty array for whole numbers. Each push! call adds one value at the end.
bag = Int[]
push!(bag, 5)
push!(bag, 8)
println(bag)
println(length(bag))Example
a = collect(1:3)
b = fill(9, 2)
c = Int[]
push!(c, 10)
println(a)
println(b)
println(c)Key points
- zeros: zeros(3) creates an array of three 0.0 values.
- ones: ones(2) creates an array of two 1.0 values.
- fill: fill(7, 3) creates an array of three copies of the value 7.
- collect: collect(1:4) turns a range into the array [1, 2, 3, 4].
- Empty array: Int[] creates an empty array that will hold whole numbers.
- push!: push! adds a value at the end of an array, so an empty array can grow.
In this example, collect builds a from the range 1:3 and fill builds b from two copies of 9. The array c starts empty as Int[], and push! adds 10, so the three prints show [1, 2, 3], [9, 9], and [10].
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What does collect(1:3) give?