Commutation matrix
In mathematics, especially in linear algebra and matrix theory, the commutation matrix is used for transforming the vectorized form of a matrix into the vectorized form of its transpose. Specifically, the commutation matrix K is the "nm" × "mn" matrix which, for any "m" × "n" matrix A, transforms vec(A) into vec(A): Here vec(A) is the "mn" × 1 column vector obtain by stacking the columns of A on top of one another: where A = [A]. In other words, vec(A) is the vector obtained by vectorizing A in column-major order. Similarly, vec(A) is the vector obtaining  by vectorizing A in row-major order. In the context of quantum information theory, the commutation matrix is sometimes referred to as the swap matrix or swap operator Code. For both square and rectangular matrices of codice_1 rows and codice_2 columns, the commutation matrix can be generated by the code below. Python. import numpy as np def comm_mat(m,n): Alternatively, a version without imports: def delta(i,j): def comm_mat(m,n): Matlab. function P = com_mat(m,n) % determine permutation applied by K A = reshape(1:m*n,m,n); v = reshape(A',1,); % apply this permutation to the rows (i.e. to each column ) of identity matrix P = eye(m*n); P = P(v,:); Example. Let formula_12 denote the following formula_13 matrix: formula_12 has the following column-major and row-major vectorizations (respectively): The associated commutation matrix is (where each formula_18 denotes a zero). As expected, the following holds: References. Category:Linear algebra Category:Matrices Category:Articles with example pseudocode