</> APL Run Loading interactive WebAssembly workspace…

🎓 Chapter 2: Vectors, Matrices & Reshaping

In traditional programming, you have integers, floats, lists, and 2D grids as distinct data structures with different methods. In APL, everything is an Array.

Array Ranks:

  • Scalar (Rank 0): A single isolated number (e.g. 42).
  • Vector (Rank 1): A 1D sequence of items (e.g. 1 2 3 4 5).
  • Matrix (Rank 2): A 2D grid with rows and columns (e.g. 3 × 4).
  • Tensor (Rank 3+): Multi-dimensional hyper-cubes.

---

1. Generating Vectors with Index Generator (⍳ N)

The Index Generator (⍳ N) (iota) generates a 1D vector of integers from 1 up to N.

> 💡 Note: In Dyalog APL default mode (⎕IO←1), indexing is 1-based, so ⍳ 5 yields 1 2 3 4 5.

⍝ Generate vector of numbers 1..12
V ← ⍳ 12
V

---

2. Inspecting Dimensions with Monadic Shape (⍴ Y)

The Shape function (⍴ Y) (rho) returns the dimensions of any array Y as a vector.

  • For a scalar 42, ⍴ 42 is empty (Rank 0).
  • For a vector V ← ⍳ 12, ⍴ V returns 12 (Rank 1, length 12).
⍝ Query shape of vector V
⍴ V

---

3. Reshaping Arrays with Dyadic Reshape (X ⍴ Y)

When ⍴ is used as a Dyadic function (X ⍴ Y), it takes the elements from vector Y on the right and arranges them into a new array with shape X on the left!

Recycling Feature:

If Y has fewer elements than requested by shape X, APL automatically recycles (repeats) Y from the beginning until shape X is filled!

⍝ Reshape 12-element vector V into a 3x4 matrix
M ← 3 4 ⍴ V
M
⍝ Recycling demonstration: fill a 4x4 matrix with pattern 1 0 1
4 4 ⍴ 1 0 1

---

4. Matrix Indexing (M[row; col])

You can access elements, entire rows, or entire columns using bracket indexing M[row; col]:

  • M[2; 3] → Element at row 2, column 3.
  • M[2; ] → Entire row 2.
  • M[ ; 3] → Entire column 3.
⍝ Extract row 2 and column 3 from matrix M
M[2; 3] ⋄ M[2; ]

← Chapter 1: Foundations of APL & Array Thinking Chapter 3: Array Arithmetic & Boolean Masks →