W3cubDocs

/Octave

21.1.1 Creating Diagonal Matrices

The most common and easiest way to create a diagonal matrix is using the built-in function diag. The expression diag (v), with v a vector, will create a square diagonal matrix with elements on the main diagonal given by the elements of v, and size equal to the length of v. diag (v, m, n) can be used to construct a rectangular diagonal matrix. The result of these expressions will be a special diagonal matrix object, rather than a general matrix object.

Diagonal matrix with unit elements can be created using eye. Some other built-in functions can also return diagonal matrices. Examples include balance or inv.

Example:

diag (1:4)
⇒
Diagonal Matrix

   1   0   0   0
   0   2   0   0
   0   0   3   0
   0   0   0   4

  diag (1:3,5,3)

⇒
Diagonal Matrix

   1   0   0
   0   2   0
   0   0   3
   0   0   0
   0   0   0

© 1996–2018 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/interpreter/Creating-Diagonal-Matrices.html