### 21.1 Creating and Manipulating Diagonal/Permutation Matrices ¶

A diagonal matrix is defined as a matrix that has zero entries outside the main
diagonal; that is,
`D(i,j) == 0`

if `i != j`

.
Most often, square diagonal matrices are considered; however, the definition
can equally be applied to non-square matrices, in which case we usually speak
of a rectangular diagonal matrix.

A permutation matrix is defined as a square matrix that has a single element
equal to unity in each row and each column; all other elements are zero. That
is, there exists a permutation (vector)
`p`

such that `P(i,j) == 1`

if `j == p(i)`

and
`P(i,j) == 0`

otherwise.

Octave provides special treatment of real and complex rectangular diagonal
matrices, as well as permutation matrices. They are stored as special objects,
using efficient storage and algorithms, facilitating writing both readable and
efficient matrix algebra expressions in the Octave language. The special
treatment may be disabled by using the functions *optimize_diagonal_matrix*
and *optimize_permutation_matrix*.

- :
`val` =

**optimize_diagonal_matrix** `()`

¶
- :
`old_val` =

**optimize_diagonal_matrix** `(``new_val`)

¶
- :
`old_val` =

**optimize_diagonal_matrix** `(``new_val`, "local")

¶
Query or set whether a special space-efficient format is used for storing
diagonal matrices.

The default value is true. If this option is set to false, Octave will store
diagonal matrices as full matrices.

When called from inside a function with the `"local"`

option, the setting
is changed locally for the function and any subroutines it calls. The original
setting is restored when exiting the function.

**See also:** optimize_range, optimize_permutation_matrix.

- :
`val` =

**optimize_permutation_matrix** `()`

¶
- :
`old_val` =

**optimize_permutation_matrix** `(``new_val`)

¶
- :
`old_val` =

**optimize_permutation_matrix** `(``new_val`, "local")

¶
Query or set whether a special space-efficient format is used for storing
permutation matrices.

The default value is true. If this option is set to false, Octave will store
permutation matrices as full matrices.

When called from inside a function with the `"local"`

option, the setting
is changed locally for the function and any subroutines it calls. The original
setting is restored when exiting the function.

**See also:** optimize_range, optimize_diagonal_matrix.

The space savings are significant as demonstrated by the following code.

x = diag (rand (10, 1));
xf = full (x);
sizeof (x)
⇒ 80
sizeof (xf)
⇒ 800