Table of Contents
Why Reshaping and Rearranging Matters
Working with vectors and matrices in MATLAB often requires changing how data is arranged without changing the data itself. Reshaping and rearranging arrays lets you change their size and layout, prepare data for algorithms, and interpret results in different forms. In this chapter you will see how to change array shapes, flip and rotate arrays, and rearrange dimensions, while understanding what stays the same and what changes.
Linear Indexing and Memory Order
To understand reshaping, it helps to remember how MATLAB stores array elements. MATLAB stores arrays column by column. For a matrix A, the elements are stored in memory in the order A(1,1), A(2,1), A(3,1), and so on down the first column, then the second column, etc.
When you reshape an array, MATLAB does not change this underlying sequence. Instead it only changes how that one-dimensional sequence is interpreted as rows, columns, and higher dimensions. This is why the total number of elements must remain constant when you reshape.
You can see this linear order with a single index like A(k). For a 2D array, A(k) moves down the first column, then continues with the second column, in the same sequence MATLAB uses internally.
Changing Shape with `reshape`
The main tool for changing the size and shape of an array is reshape. It creates a new array that has the same elements as the original, in the same column-wise order, but arranged into a new size.
The basic form is
B = reshape(A, m, n);
Here A is the original array and B is the reshaped version. The new array B has m rows and n columns, and numel(A) must equal m*n. The underlying data are read in column-wise order from A and filled column-wise into B.
For example, if A is a 2 by 6 matrix, and you call
B = reshape(A, 3, 4);
then B will be a 3 by 4 matrix. The first 3 elements in column-major order from A fill the first column of B, the next 3 fill the second column of B, and so on.
You can also reshape into more than two dimensions. For instance,
C = reshape(A, 2, 3, 4);
creates a 2 by 3 by 4 array as long as numel(A) equals 234. MATLAB still takes the elements from A using its linear order and fills the new array along the first dimension fastest, then the second, then the third.
Using `[]` for Automatic Dimension Inference
You often know one dimension of the desired shape but do not want to compute the other one. MATLAB lets you put [] as one of the size arguments to reshape. MATLAB then automatically computes that dimension so that the number of elements stays the same.
For example
B = reshape(A, 3, []);
reshapes A into a matrix with 3 rows and as many columns as needed, which is numel(A)/3. You must still ensure that numel(A) is divisible by 3, otherwise MATLAB returns an error.
The same idea applies to higher dimensions. Something like
C = reshape(A, 2, [], 5);
lets MATLAB compute the middle dimension, provided numel(A) is divisible by 2*5.
Transforming Matrices with `transpose` and `permute`
Changing shape is different from swapping dimensions. Transposing a matrix with the ' or .' operator swaps rows and columns. The number of elements stays the same, but the dimensions change from m by n to n by m.
The operator ' is the complex conjugate transpose, which both transposes and conjugates complex numbers. The operator .' is the nonconjugate transpose, which only swaps rows and columns and leaves complex values unchanged.
For arrays with more than two dimensions, you use permute to rearrange dimensions. The syntax
B = permute(A, order);
creates a new array B whose dimensions are rearranged according to the vector order. If A has size [d1 d2 d3], and you call
B = permute(A, [2 1 3]);
then B has size [d2 d1 d3]. The data are not reordered arbitrarily. Instead MATLAB maps indices systematically. An element A(i,j,k) moves to B(j,i,k).
The inverse operation of permute is ipermute. It returns the original dimension arrangement when you give it the same permutation vector.
Collapsing and Restoring Dimensions with `squeeze`
Sometimes arrays gain singleton dimensions, which are dimensions of size 1. These dimensions can appear after operations like indexing or certain calculations. These dimensions may be inconvenient when you want to use functions that expect 2D matrices or vectors.
The squeeze function removes singleton dimensions from an array. For example, if A has size [1 4 1 5] then squeeze(A) has size [4 5]. The data remain the same in linear order, but the unnecessary size-1 dimensions are taken out.
Be careful when using squeeze on row and column vectors. A 1 by N row vector does not lose its first dimension, since it is size 1 but must remain to keep the array as a 2D matrix with one row. squeeze removes only dimensions beyond the second when dealing with vectors and matrices. It is useful when a 3D or 4D result has extra size-1 dimensions that you want to eliminate.
Flattening Arrays into Vectors
You may want to treat any array as a single vector of all its elements. For this, MATLAB provides the (:) indexing pattern. Writing
v = A(:);
creates a column vector that contains every element of A in column-major order. This does not change A. It simply gives you a new 1D view.
You can then reshape this vector back into some other shape using reshape. This is often used to flatten multi-dimensional data for an algorithm that expects a vector, followed by reshaping results back into the original layout.
If you need a row vector instead of a column vector, you can combine (:) with a transpose, for example
r = A(:).';which gives a 1 by N row vector.
Flipping and Rotating Arrays
Rearranging data often means reversing orders or rotating orientations. MATLAB provides functions that operate along specific dimensions without changing the overall shape.
The function flip reverses the order of elements along a given dimension. The call
B = flip(A, 1);
reverses the order of rows of A, while
B = flip(A, 2);
reverses the order of columns. If you omit the dimension, flip reverses along the first non-singleton dimension.
For two-dimensional matrices, there are also convenient functions flipud and fliplr. The function flipud(A) flips a matrix up to down, reversing row order. The function fliplr(A) flips a matrix left to right, reversing column order. Both preserve the size of the matrix.
Rotations in multiples of 90 degrees are handled by the rot90 function. The basic form
B = rot90(A);
rotates the matrix A by 90 degrees counterclockwise. You can rotate by multiples of 90 degrees by providing a second integer argument. For example rot90(A, 2) rotates by 180 degrees, and rot90(A, -1) rotates by 90 degrees clockwise. These operations keep the matrix elements but move them to new positions, and they often swap the row and column sizes unless the matrix is square.
Rearranging Higher Dimensions with `shiftdim` and `circshift`
For arrays with more than two dimensions, you may want to rearrange dimensions in a systematic way. While permute lets you specify an arbitrary ordering of dimensions, there are two more focused tools for particular patterns.
The function shiftdim shifts the order of dimensions to the left or to the right. When you call
B = shiftdim(A, n);
with a positive n, MATLAB removes the first n dimensions and appends them at the end. For example, if A has size [2 3 4 5] and you call shiftdim(A, 1), then B has size [3 4 5 2]. This is similar to permute, but only for circular shifts of the dimension list.
If you call shiftdim without a second argument, it removes leading singleton dimensions and returns how many were removed. This is useful if your data has unnecessary size-1 dimensions at the front.
The function circshift is different. It does not change the size or the list of dimensions, but instead shifts the data within each dimension in a circular fashion. For example
B = circshift(A, 1);
shifts all elements of A by one position along the first dimension. Elements that fall off one end reappear at the other end. With a vector of shifts, for example
B = circshift(A, [0 2]);
MATLAB shifts A by zero along the first dimension and by two along the second dimension. This is useful for periodic or wraparound behaviors where you want to rotate data indices rather than change the array shape.
Resizing by Adding or Removing Elements
Some rearrangements require you to change the number of elements. This is different from pure reshaping, because now you are not just reinterpreting the same data but adding or removing entries.
For simple 2D cases, you can grow or shrink matrices through indexing and assignment. For example, setting
A(5, 7) = 0;
on a smaller matrix expands it to at least 5 by 7, and new elements are filled with zeros. To remove rows or columns, you can assign [] to parts of the matrix, for instance
A(3, :) = [];
which deletes the third row. This kind of resizing is not a mere reshaping of existing data. It modifies the total number of elements. It is important to distinguish this from reshape, which always preserves numel(A).
For images or signals you might use specialized resizing functions that interpolate or decimate data. Those go beyond straightforward rearrangement and involve changing the values as well.
Combining Reshaping with Indexing
Reshaping becomes powerful when you combine it with indexing operations. For example, you can reshape a 2D matrix into a long vector, apply some operation that works naturally on a vector, then reshape the result back to the original shape.
A typical pattern is
sz = size(A);
v = A(:);
% operate on v
A_new = reshape(v, sz);
Since A_new uses the same dimensions as A, you restore the initial layout after whatever vectorized operation you applied.
You can also use logical indexing on a reshaped vector to work on selected elements regardless of their original position. After modifying the vector, you reshape it back to recover a matrix or higher-dimensional array with edited entries in their original locations.
The important idea is that reshaping never copies or reorders values in a logical pattern; it only changes how indices map to that fixed linear sequence. Indexing, on the other hand, chooses which elements to read or write from that sequence.
Important points to remember:
reshapekeeps the total number of elements the same and uses MATLAB's column-wise order.- You can use
[]inreshapeto let MATLAB infer one dimension automatically. transpose,permute, andipermuterearrange dimensions, not the linear ordering of elements.squeezeremoves singleton dimensions, and(:)flattens any array into a column vector.flip,flipud,fliplr,rot90,shiftdim, andcircshiftrearrange positions of elements but keep the array size or set of dimensions.- Changing the number of elements is not reshaping; it requires indexing or other operations that add or remove elements.