Skip to content

shiftdim

Shift dimension

shiftdim(A, k)

  • A should be array and k should be an integer scalar. It shifts A’s dimensions k times.
  • If k is positive, it shifts to the left in a cyclic manner. See Example 1 below.
  • If k is negative, it shifts to the right and creates k leading singleton dimensions. See Example 2 below.

Example 1: In this example, a has size [1, 2, 3]. Its dimensions are shifted to the left by 1 in a cyclic manner. Thus, the output has size [2, 3, 1].

a=randi(10,1,2,3)
shiftdim(a,1)
a(:, :, 1) =

1.000   8.000

a(:, :, 2) =

6.000   5.000

a(:, :, 3) =

7.000   9.000

ans =
1.000   6.000   7.000
8.000   5.000   9.000

Example 2: Here k is negative (k == -2) and dimensions are shifted to the right. Newly created leading dimensions are singleton.

a=randi(10,1,2,3);
% Size before shifting
size(a)
b=shiftdim(a,-2);
% Size after shifting to the right
size(b)
ans =
 1.000   2.000   3.000

ans =
 1.000   1.000   1.000   2.000   3.000

[M,d] = shiftdim(A)

  • It removes the leading singleton dimensions of A. d is the number of leading singleton dimensions removed, and M is the array obtained after removing the leading dimensions.

Example 3: In this example, a has size [1, 1, 2, 3], where the first two dimensions are singleton. shiftdim() removes the singleton dimensions to give M, which has size [2, 3]. d is equal to 2 because two singleton dimensions have been removed.

a=rand(1,1,2,3)
[M,d]=shiftdim(a)
a(:, :, 1, 1) = 1e-1 × 

 1.656

a(:, :, 2, 1) = 1e-1 × 

 4.799

a(:, :, 1, 2) = 1e-1 × 

 5.045

a(:, :, 2, 2) = 1e-1 × 

 3.262

a(:, :, 1, 3) = 1e-1 × 

 2.712

a(:, :, 2, 3) = 1e-1 × 

 5.207

M = 1e-1 × 
 1.656   5.045   2.712
 4.799   3.262   5.207

d =
 2.000