# diag() Function & Examples

Use the diag() matrix function in Calcul.io. Review its syntax, edit working examples, understand the result, and explore related math functions.

## diag

#### diag(x)

#### diag(x, k)

Try it yourself:

```calculio
diag(1:3)
diag(1:3, 1)
a = [1, 2, 3; 4, 5, 6; 7, 8, 9]
diag(a)
```

[concat](https://calcul.io/function/concat/index.md)

[det](https://calcul.io/function/det/index.md)

[identity](https://calcul.io/function/identity/index.md)

[inv](https://calcul.io/function/inv/index.md)

[ones](https://calcul.io/function/ones/index.md)

[range](https://calcul.io/function/range/index.md)

[size](https://calcul.io/function/size/index.md)

[squeeze](https://calcul.io/function/squeeze/index.md)

[subset](https://calcul.io/function/subset/index.md)

[trace](https://calcul.io/function/trace/index.md)

[transpose](https://calcul.io/function/transpose/index.md)

[zeros](https://calcul.io/function/zeros/index.md)

---

## 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()](https://calcul.io/function/identity/index.md) to construct simple matrix expressions, or [trace()](https://calcul.io/function/trace/index.md) 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()](https://calcul.io/function/size/index.md) to verify shape, and [zeros()](https://calcul.io/function/zeros/index.md) 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()](https://calcul.io/function/dotMultiply/index.md); for ordinary matrix multiplication, use [multiply()](https://calcul.io/function/multiply/index.md).

[All functions](https://calcul.io/functions/index.md)
