Tutorial

How to Transpose a Multidimensional Matrix in MATLAB

The function permute rearranges the dimensions of a matrix.

Preparation

Create a matrix using the following code:

A = reshape(1:12,2,3,2);
sizeA = size(A);

Syntax

B = permute(A,order) rearranges the dimensions of A so that they are in the order specified by the vector order, and stores the result in B. All values in order must be integers greater than zero and cannot be repeated.

Given a value \(j\) at the \(i\)-th position in order, for each element in A, its subscript at the \(i\)-th dimension is replaced by its subscript at the \(j\)-th dimension (Table 1).

Table 1. Movement of a sample point at \((5,7,3)\) according to various order vectors.
Vector New position
\([1,2,3]\) Stays at the same position
\([2,1,3]\) Moves to \((7,5,3)\)
\([1,3,2]\) Moves to \((5,3,7)\)
\([3,2,1]\) Moves to \((3,7,5)\)

Note: The number of elements in order must be greater than or equal to the number of dimensions in A. In most cases it is equal.

Examples

permute is generally used to transpose multidimensional matrices.

Multidimensional matrix: Matrix with more than two dimensions.
% Swap rows and columns
resultExample1 = permute(A,[2,1,3]);
sizeExample1 = size(resultExample1);
% Swap rows and planes
resultExample2 = permute(A,[3,2,1]);
sizeExample2 = size(resultExample2);
% Swap columns and planes
resultExample3 = permute(A,[1,3,2]);	
sizeExample3 = size(resultExample3);

Further reading

I recommend the following books to learn more on matrix manipulation in MATLAB.

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a 2017 Textbook Excellence Award. The second chapter explains how to perform a wide list of operations on matrices, including the transpose operation.

  2. MATLAB for Engineers (5th Edition)

    This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. Matrix manipulation is explained in the fourth chapter.

I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.

doc permute;

Exercise

Create a matrix using the following code:

X = reshape(1:30,2,5,3);
  1. Swap rows and columns in X, and store the result in a new matrix X1
  2. Swap columns and planes in X, and store the result in a new matrix X2
  3. Verify the element at \((1,2,1)\) in X is now at \((2,1,1)\) in X1
  4. Verify that the element at \((2,4,2)\) in X is now at \((2,2,4)\) in X2

Source code

I hope you have learned how to transpose a multidimensional matrix in MATLAB. The source code developed in this tutorial is available at this page.

Share

Your friends may need this knowledge to complete a task. Share this tutorial.