Skip to content

permute

Rearranging dimensions

b = permute(a, order)

  • a is an array of any number of dimensions.
  • It rearranges the dimensions of a according to the order specified by order, such that the order(i)-th dimension of a is moved to the i-th dimension in the new array b.
  • It's like an inverse operation of ipermute. See Example 2 below.
  • order should be a permutation of the vector 1:length(order). If order is multi-dimensional, it will be treated as a vector and hence indexed linearly.
  • Elements in order should be all positive and not exceeding length(order).

Note

If length(order) exceeds ndims(a), the trailing dimensions of a are considered as singleton. See Example 3 below.

Example 1: Swapping 1st and 2nd dimenions. This is the same as taking transpose of a.

a=[1 2 3;4 5 6];
permute(a,[2 1])
ans =
 1.000   4.000
 2.000   5.000
 3.000   6.000

Example 2: permute is just like an inverse operation of ipermute.

a=rand(3,4);
b=ipermute(a,[3 1 4 2 5]);
c=permute(b,[3 1 4 2 5]);

% a and c have the same sizes
size(a),size(c)

% a and c are the same matrices
a-c
ans =
 3.000   4.000

ans =
 3.000   4.000

ans =
 0.000   0.000   0.000   0.000
 0.000   0.000   0.000   0.000
 0.000   0.000   0.000   0.000

Example 3: Here, order has a length larger than ndims(a). Thus, 3rd, 4th, and 5th dimensions of a are considered as singleton, i.e., having lengths of 1. The 5th dimension of b is singleton, and therefore ndims(b) is 4.

a=rand(3,4);
b=permute(a,[3 1 4 2 5]);
size(b)
ndims(b)
ans =
 1.000   3.000   1.000   4.000

ans =
 4.000