W3cubDocs

/Octave

21.1.2 Creating Permutation Matrices

For creating permutation matrices, Octave does not introduce a new function, but rather overrides an existing syntax: permutation matrices can be conveniently created by indexing an identity matrix by permutation vectors. That is, if q is a permutation vector of length n, the expression

P = eye (n) (:, q);

will create a permutation matrix - a special matrix object.

eye (n) (q, :)

will also work (and create a row permutation matrix), as well as

eye (n) (q1, q2).

For example:

eye (4) ([1,3,2,4],:)
⇒
Permutation Matrix

   1   0   0   0
   0   0   1   0
   0   1   0   0
   0   0   0   1

  eye (4) (:,[1,3,2,4])
⇒
Permutation Matrix

   1   0   0   0
   0   0   1   0
   0   1   0   0
   0   0   0   1

Mathematically, an identity matrix is both diagonal and permutation matrix. In Octave, eye (n) returns a diagonal matrix, because a matrix can only have one class. You can convert this diagonal matrix to a permutation matrix by indexing it by an identity permutation, as shown below. This is a special property of the identity matrix; indexing other diagonal matrices generally produces a full matrix.

eye (3)
⇒
Diagonal Matrix

   1   0   0
   0   1   0
   0   0   1

  eye(3)(1:3,:)
⇒
Permutation Matrix

   1   0   0
   0   1   0
   0   0   1

Some other built-in functions can also return permutation matrices. Examples include inv or lu.

© 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-Permutation-Matrices.html