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().

Try Diag in Calcul.io

Start with one of the editable examples above, then replace its arguments with your own values. Keeping the function on a separate calculator line makes the input and result easy to compare. For a longer workflow, assign the result to a variable or reference that line in the next expression.

Check the shown signature before adding optional arguments, and use the related-function links to compare operations with similar purposes.

All functions