diag

diag(x)

diag(x, k)

Try it yourself:


diag(): Creating and Reading Matrix Diagonals

diag() works with the main diagonal of a matrix. Depending on the input, it can create a diagonal matrix from a vector or extract diagonal entries from a matrix. Diagonal matrices are valuable because their nonzero values stay on one line from top left to bottom right.

Typical uses

diag([2, 3, 4]) represents a matrix that scales the three coordinate axes independently. Extracting the diagonal is useful for reading variances, coefficients, or self-connections stored in a square matrix. Combine it with identity() to construct simple matrix expressions, or trace() to sum the diagonal entries.

Check orientation and dimensions before using a vector as a diagonal. A diagonal matrix is square, and the number of supplied entries determines both dimensions. Use size() to verify shape, and zeros() when you need an explicitly sized starting matrix.

Matrix context

Diagonal structure makes multiplication efficient and easy to reason about: multiplying by a diagonal matrix scales matching components rather than mixing them. For element-wise operations, choose dotMultiply(); for ordinary matrix multiplication, use multiply().

All functions