Julia Nested Arrays
A nested array is an array whose items are themselves arrays. It stores data in rows, like a small grid.
Build a nested array
Inner arrays sit inside one outer array. The whole value prints with both rows visible.
grid = [[1, 2], [3, 4]]
println(grid)
println(length(grid))Double indexing reaches one item
The first index picks an inner array. The second index picks an item inside it.
grid = [[1, 2], [3, 4]]
println(grid[2][1])
println(grid[1][2])Print a grid row by row
A function loops over the outer array. Each round prints one inner array.
function printgrid(grid)
for row in grid
println(row)
end
end
printgrid([[1, 2], [3, 4], [5, 6]])Example
function total(grid)
s = 0
for row in grid
for value in row
s += value
end
end
return s
end
grid = [[1, 2], [3, 4]]
println(grid[2][2])
println(total(grid))Key points
- Nested array: an array that holds other arrays as its items.
- Build one by writing inner arrays inside an outer array, like [[1, 2], [3, 4]].
- Use two indexes to reach one item, first the inner array and then the position inside it.
- The first index picks a row in [[1, 2], [3, 4]].
- Printing a nested array shows the inner arrays in order.
In this example, the grid holds two inner arrays of two numbers each. The double index grid[2][2] reaches 4 in the second row. The total function adds every value in every row and returns 10.
Note
Julia nested arrays are arrays of arrays, so each inner array can have its own length.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
For grid = [[1, 2], [3, 4]], what is grid[1][2]?