liveBook · Manning

Slicing

As explained in Julia as a Second Language

Array slicing is the selection of one or more elements or subarrays from an array by specifying index ranges or positions.

Array slicing selects elements or subarrays with positions and ranges. In Julia, square-bracket access handles both retrieval and assignment, so the same notation works for vectors, matrices, and higher-dimensional arrays. section 14.4 section 14.7

Build slices incrementally:

  • Use one-based positions such as A[3], or use begin and end when the exact array length should not matter: A[begin+2] and A[end-1]. section 14.4
  • Use ranges such as A[2:5] to select several elements, and A[:] to select every element. section 14.4
  • Apply row and column ranges to matrices; A[:, 4] selects a column, while A[2, :] selects a row. section 14.4
  • Remember that ordinary slices return copies. Use @view when a slice should refer directly to the original data and avoid copying. section 14.4 section 14.7

Copy or view?

julia> A = [8, 1, 2, 7]; julia> B = A[:]; julia> B[2] = 42 julia> A [8, 1, 2, 7] A[:] creates an independent copy. By contrast, B = @view A[3:end] creates a view; assigning B[2] = 1331 also changes the corresponding element of A. This distinction matters when repeated slicing would copy large arrays. section 14.4

Table 14.1 Relation between element access and Julia function calls (view table figure)

Syntax sugar

Translates to

Description

xs[i]

getindex(xs, i)

Get element at index i

xs[i,j]

getindex(xs, i, j)

Get element at row i and column j

xs[i] = 42

setindex!(xs, 42, i)

Set element at index i

xs[i,j] = 42

setindex!(xs, 42, i, j)

Set element at row i and column j

Map square-bracket element access and assignment to the underlying getindex and setindex! function calls. section 14.4

How Julia as a Second Language covers it

How deep it goes
Explains one- and two-dimensional syntax, begin/end indexing, copy semantics, views, and underlying indexing functions.
Examples
Demonstrates vector ranges, begin/end positions, matrix row and column selection, copied slices, and @view mutations.
What it assumes
Assumes basic Julia arrays and indexing while establishing one-based positions, ranges, and multidimensional selection.
What you can do after
Apply it via Julia indexing syntax to select array data, preserve or share storage, and avoid unnecessary copies.
How it connects
Connects arrays with vectors, matrices, indexing, ranges, copies, views, and mutation.

Also explained in

Compare how 16 books explain slicing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.