Working with arrays

Introduction to Julia

James Fulton

Climate informatics researcher

Adding an element to the end of an array

# Predefine array
x = [1,2,3,4]

# Add the number 5 to end of array push!(x, 5)
println(x)
[1,2,3,4,5]
Introduction to Julia

Adding an element to the end of an array

# Predefine array
x = [1,2,3,4]

# Add the float 5.0 to end of array
push!(x, 5.0)


println(x) println(eltype(x))
[1,2,3,4,5]
Int64
Introduction to Julia

Adding an element to the end of an array

# Predefine array
x = [1,2,3,4]

# Add the float 5.2 to end of array
push!(x, 5.2)
ERROR: InexactError: Int64(5.2)
Introduction to Julia

Creating an array of given type

# Create float array
x = Float64[1,2,3,4]

println(typeof(x))


# Add the float 5.2 to end of array push!(x, 5.2) println(x)
Vector{Float64}

[1.0, 2.0, 3.0, 4.0, 5.2]
Introduction to Julia

Creating an array of given type

# Create empty float array
x = Float64[]

println(typeof(x))
println(x)
Vector{Float64}
Float64[]
Introduction to Julia

Creating an array of given type

# Create empty string array
x = String[]

println(typeof(x))
println(x)
Vector{String}
String[]
Introduction to Julia

Adding elements to the end of an array

# Create empty string array
x = String[]

# Add some elements to the array
push!(x, "one") 
push!(x, "two") 
push!(x, "three") 

println(x)
["one", "two", "three"]
# Create empty string array
x = String[]

# Add some elements to the array
append!(x, ["one", "two", "three"])




println(x)
["one", "two", "three"]
Introduction to Julia

Removing the last element

x = [1,2,3,4]

# Remove 1 element from end
x = x[1:end-1]

println(x)

[1, 2, 3]
x = [1,2,3,4]

# Remove 1 element from end
last_element = pop!(x)


println(x) println(last_element)
[1, 2, 3]
4
Introduction to Julia

Creating array of defined length

# Create integer array with 4 zeros
x = zeros(Int64, 4)


println(x)
[0, 0, 0, 0]
Introduction to Julia

Replacing an element

# Create integer array with 4 zeros
x = zeros(Int64, 4)

# Replace element in position 3 with value 1
x[3] = 1


println(x)
[0, 0, 1, 0]
Introduction to Julia

Replacing many elements

# Create integer array with 4 zeros
x = zeros(Int64, 4)

# Replace many elements
x[2:3] = [2,3]


println(x)
[0, 2, 3, 0]
Introduction to Julia

Cheatsheet

  • Add single element - push!(x, 1)
  • Add many elements - append!(x, [1,2,3])
  • Remove last element - pop!(x)
  • Create array of given type - Int64[1,2,3], Float64[1,2,3], etc.
  • Create empty array of given type -Int64[], Float64[], etc.
  • Create an array full of zeros - zeros(Int64, n)
  • Replace element - x[index] = value
  • Replace many elements - x[a:b] = [value1, value2, ...]
Introduction to Julia

Let's practice!

Introduction to Julia

Preparing Video For Download...