Jump to navigation Jump to search
Swaps two subsystems within a state or operator

Other toolboxes required none
Related functions PermutationOperator
Function category Permutations and symmetry of subsystems

Swap is a function that swaps the position of two subsystems in the space on which a quantum state or operator live. Note that the state or operator can have more than two subsystems altogether – the remaining subsystems are not affected. To permute the positions of more than two subsystems, use the PermuteSystems function.


  • SX = Swap(X)
  • SX = Swap(X,SYS)
  • SX = Swap(X,SYS,DIM)

Argument descriptions

  • X: a vector (e.g., a pure quantum state) or a matrix to have its subsystems permuted
  • SYS (optional, default [1,2]): a 1-by-2 vector containing the indices of the subsystems to be swapped
  • DIM (optional, by default has all subsystems of equal dimension): A specification of the dimensions of the subsystems that X lives on. DIM can be provided in one of three ways:
    • If DIM is a scalar, it is assumed that X lives on the tensor product of two spaces, the first of which has dimension DIM and the second of which has dimension length(X)/DIM.
    • If $X \in M_{n_1} \otimes \cdots \otimes M_{n_p}$ then DIM should be a row vector containing the dimensions (i.e., DIM = [n_1, ..., n_p]).
    • If the subsystems aren't square (i.e., $X \in M_{m_1, n_1} \otimes \cdots \otimes M_{m_p, n_p}$) then DIM should be a matrix with two rows. The first row of DIM should contain the row dimensions of the subsystems (i.e., the mi's) and its second row should contain the column dimensions (i.e., the ni's). In other words, you should set DIM = [m_1, ..., m_p; n_1, ..., n_p].
  • ROW_ONLY (optional, default 0): If set equal to 1, only the rows of X are permuted (this is equivalent to multiplying X on the left by SwapOperator(DIM,SYS)). If equal to 0, both the rows and columns of X are permuted (this is equivalent to multiplying X on both the left and right by the swap operator).


The following code constructs a 4-by-4 matrix (thought of as an operator in $M_2 \otimes M_2$) and then swaps the two subsystems, which is equivalent to multiplying on the left and right by the swap operator:

>> X = reshape(1:16,4,4)

X =

     1     5     9    13
     2     6    10    14
     3     7    11    15
     4     8    12    16

>> Swap(X)

ans =

     1     9     5    13
     3    11     7    15
     2    10     6    14
     4    12     8    16

>> SwapOperator(2)*X*SwapOperator(2)

ans =

     1     9     5    13
     3    11     7    15
     2    10     6    14
     4    12     8    16

Source code

Click here to view this function's source code on github.