JULIA / CHAPTER 03

Arrays, indexing, and broadcasting

Intermediate

Distinguish mutation, copying, and elementwise operations.

By the end of this chapter

  • Use one-based array indices
  • Explain aliases and shallow copies
  • Broadcast a function across array elements

The idea

Ordinary Julia arrays use one-based indices, and multidimensional arrays accept one index per dimension. An array is mutable: assigning to an indexed position changes the existing object. Assigning an array to another variable creates another reference to that same object. copy creates a separate outer array, but nested mutable elements are still shared, so choose a deeper copying policy only when the data model requires it.

Broadcasting applies an operation across compatible shapes. A dotted call such as abs.(values) applies a function elementwise, and a dotted operator such as values .+ 2 combines every element with a scalar. Plain matrix operations have their own algebraic meaning, so dots are a deliberate part of the expression. eachindex provides suitable indices for generic array iteration instead of assuming every array uses a particular index range.

Julia example
original = [2, 4, 6]
separate = copy(original)
separate[1] = 9
shifted = original .+ 3
println(original[1])
println(join(shifted, ","))
grid = [1 2; 3 4]
println(grid[2, 1])
Result
2
5,7,9
3

Changing the copied outer array leaves the original numbers untouched. Broadcasting adds three to each original entry, and the matrix lookup selects row two, column one.

Try it yourself

Return a new vector containing the square of every input value without modifying the input.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What does this print?
a = [1, 2]
b = a
b[1] = 8
println(a[1])