Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 45 ยท Matrices and Arrays

Reshaping, Joining and Sorting

Reshape arrays, join them with horzcat, vertcat and cat, and sort with sort, sortrows and unique in MATLAB and Octave, with Python stand-ins.

Most array work is rearranging: turning a long vector into a table, gluing two tables together, putting rows in order or removing duplicates. MATLAB and Octave have a small, consistent set of functions for this, and almost all of them rely on one fact you should keep in mind: arrays are stored column by column.

This lesson covers reshape, joining with brackets, horzcat, vertcat and cat, dimension shuffling with permute and squeeze, and ordering with sort, sortrows, unique, flip and circshift. If indexing is still new, review Indexing and Slicing first.

MATLAB and Octave are not installed on this site, so the matlab blocks are read-only. The runnable TryIt blocks are NumPy stand-ins. NumPy fills arrays row by row by default, so the stand-ins pass order="F" where MATLAB's column-by-column behavior matters.

Three families of rearranging

Reshape Same elements, new shape.
Join Glue arrays side by side or stacked.
Order Sort, flip, shift and remove duplicates.

None of them changes the original unless you assign the result back.

1 / 2

reshape

reshape(A, m, n) returns an array with the same elements arranged in m rows and n columns. The element count must not change, and the elements are read and written down the columns:

MATLAB
v = 1:6;
A = reshape(v, 2, 3)
%    1   3   5
%    2   4   6

reshape(A, 3, 2)
%    1   4
%    2   5
%    3   6

reshape(A, 1, [])    % [] means "work this size out": 1 2 3 4 5 6
A(:)                 % all elements as one column

Use [] for at most one size to let MATLAB compute it. A request that does not divide evenly, such as reshape(1:6, 4, []), raises an error. A(:) is the quickest way to flatten any array to a column, and A(:)' gives a row.

Python reshape is column-major

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first two prints show the trap: the same six numbers fill the 2-by-3 shape differently depending on the language's storage order. When you port code between MATLAB and NumPy, this is the most common silent difference.

Joining arrays

Square brackets join arrays. A space or comma joins horizontally (columns side by side); a semicolon joins vertically (rows stacked):

MATLAB
B = [1 2; 3 4];
C = [10 20; 30 40];

[B C]     % 1 2 10 20 ; 3 4 30 40   same as horzcat(B, C)
[B; C]    % 4-by-2                   same as vertcat(B, C)

The sizes must agree along the joined edge: [B C] needs the same number of rows, [B; C] the same number of columns. A mismatch gives an error such as "Dimensions of arrays being concatenated are not consistent."

For any number of dimensions use cat(dim, A, B, ...). cat(1, ...) is vertcat, cat(2, ...) is horzcat, and cat(3, ...) stacks matrices into pages of a 3-D array:

MATLAB
S = cat(3, B, C);   % 2x2x2 array
size(S)             % 2 2 2
S(:, :, 2)          % the second page: C

Related helpers are repmat(A, m, n) to tile a block and blkdiag to build block-diagonal matrices. Use horzcat and vertcat instead of brackets when you build the list of arrays programmatically, for example with a cell array: vertcat(parts{:}).

permute and squeeze

A 3-D array has dimensions 1 (rows), 2 (columns) and 3 (pages). permute(X, order) reorders the dimensions, and squeeze(X) removes dimensions of size 1. Together they let you slice a 3-D array and get something you can print or plot.

MATLAB
X = reshape(1:24, 2, 3, 4);
size(X)                     % 2 3 4
Y = permute(X, [3 1 2]);
size(Y)                     % 4 2 3
Y(3, 2, 1) == X(2, 1, 3)    % true: the subscripts are shuffled the same way

slab = X(:, 1, :);          % 2x1x4 - awkward
size(squeeze(slab))         % 2 4

For 2-D arrays, permute(A, [2 1]) is the same as the transpose A.'. Note that squeeze only matters for arrays of more than two dimensions: a row or column vector keeps its shape.

Python 3-D arrays: permute and squeeze

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice how the stand-in subtracts one from every index: Python counts from 0, MATLAB from 1. The relationship Y(3,2,1) == X(2,1,3) holds because permute(X, [3 1 2]) makes the old dimension 3 the new dimension 1.

sort and sortrows

sort(x) returns the values in ascending order. Add 'descend' for the other direction, and ask for a second output to get the permutation that sorted the data:

MATLAB
x = [7 3 9 3 5];
sort(x)               % 3 3 5 7 9
sort(x, 'descend')    % 9 7 5 3 3
[s, i] = sort(x);     % i = 2 4 5 1 3

The sort is stable: equal values keep their original order, which is why index 2 comes before 4. On a matrix, sort(A) sorts each column separately; sort(A, 2) sorts each row. The index output is the key to sorting one array by another: names(i) puts names in the order of the scores.

sortrows sorts whole rows by one or more key columns, keeping each row together. A negative column number means descending:

MATLAB
T = [3 90; 1 75; 2 90; 1 60];
sortrows(T)           % by column 1, then 2:  1 60; 1 75; 2 90; 3 90
sortrows(T, [-2 1])   % score descending, then id: 2 90; 3 90; 1 75; 1 60

unique, flip and circshift

unique(x) returns the sorted distinct values. Extra outputs tell you where each value came from. Use 'stable' to keep the order of first appearance instead of sorting:

MATLAB
w = [5 2 5 9 2];
unique(w)             % 2 5 9
unique(w, 'stable')   % 5 2 9
[u, ia, ic] = unique(w);
% u(ic) reconstructs w; w(ia) equals u

For cell arrays of text, unique works too, which makes it a good way to list the categories in a column.

To reverse and rotate, use flip (or fliplr and flipud for the two matrix directions), rot90, and circshift. circshift(x, k) moves elements k places to the right, wrapping around; a negative k moves left.

MATLAB
flip(1:5)             % 5 4 3 2 1
circshift(1:5, 2)     % 4 5 1 2 3
circshift(1:5, -1)    % 2 3 4 5 1
rot90([1 2; 3 4])     % 2 4 ; 1 3  (counterclockwise)
Python Sorting, unique and shifting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

np.lexsort takes its keys in the opposite order to sortrows: the last key listed is the primary one. That is why the stand-in lists column 2 before column 1.

sort, sortrows and unique all return a permutation or index vector if you ask for it. Use it to keep several parallel arrays in step instead of sorting each one separately.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does reshape(1:6, 2, 3) return?

    MATLAB fills the new shape column by column, so the first column is 1, 2, the second is 3, 4 and the third is 5, 6.
  2. 2. Which expression stacks matrices B and C on top of each other?

    A semicolon starts a new row, so [B; C] (or vertcat(B, C)) stacks them. [B C] places them side by side and cat(3, ...) makes a 3-D array.
  3. 3. What does sortrows(T, -2) do?

    sortrows moves whole rows. The sign of the column number selects the direction, and the number selects the key column.
  4. 4. What is circshift(1:5, -1)?

    A negative shift moves elements left with wraparound: the first element reappears at the end.
  5. 5. Which call keeps duplicates out but preserves the order of first appearance?

    By default unique also sorts. The 'stable' option keeps the order in which each value first appeared.

Summary

  • reshape keeps the elements and the column-major order; use [] to let one size be computed, and A(:) to flatten.
  • Brackets join arrays (space for side by side, semicolon for stacked); horzcat, vertcat and cat(dim, ...) do the same programmatically, and sizes must match on the joined edge.
  • permute reorders dimensions and squeeze drops dimensions of size 1.
  • sort works per column by default, is stable and can return the permutation; sortrows sorts whole rows by key columns.
  • unique returns sorted distinct values (or first-appearance order with 'stable'); flip, rot90 and circshift reverse and rotate.
  • Python and NumPy are row-major and 0-based, so stand-ins need order="F" and index shifts to match MATLAB.

Next: learn how operators treat whole arrays in Arithmetic: Matrix vs Element-wise.