Skip to content
LumenaryAcademy
Foundations 50 min

Matrices, arrays and indexing

Building arrays with brackets, ranges and constructor functions, and reading and changing them with subscripts, linear indices and logical masks.

Code tested · 5AI-draftedAwaiting review by a computer scientist
MotivationH

Thinking in arrays

A weather station records a temperature every hour. A photograph is a grid of brightness values. A survey stores one row per person and one column per question. In each case the natural unit is not a single number but a whole array of them, and the questions you ask are about many elements at once: which hours were above 26 degrees? What is the average of the third column? Replace every negative reading with zero.

In MATLAB and Octave these questions have short answers, because the language has a rich vocabulary for building arrays and for indexing them: picking out rows, columns, blocks, individual elements, or every element that satisfies a condition. Indexing is where most of the power, and most of the beginner bugs, are. This lesson takes it slowly.

One remark about output before you start. In this lesson most statements are left without a semicolon, so you can see each array as Octave displays it. MATLAB shows the same numbers with slightly different spacing and blank lines.

Worked examplesH

Creating arrays

matlab
a = [1 2 3]
b = [4; 5; 6]
c = 0:0.25:1
d = linspace(0, 1, 5)
Z = zeros(2, 3)
I = eye(3)
R = repmat([1 2], 2, 2)
M = magic(3)
text
a =

   1   2   3

b =

   4
   5
   6

c =

         0    0.2500    0.5000    0.7500    1.0000

d =

        0   0.2500   0.5000   0.7500   1.0000

Z =

   0   0   0
   0   0   0

I =

Diagonal Matrix

   1   0   0
   0   1   0
   0   0   1

R =

   1   2   1   2
   1   2   1   2

M =

   8   1   6
   3   5   7
   4   9   2

Definition— Brackets and separators

Inside square brackets, a space or comma separates elements of a row, and a semicolon (or a line break) starts a new row. [1 2 3] is a 1-by-3 row vector, [4; 5; 6] a 3-by-1 column vector, and [1 2; 3 4] a 2-by-2 matrix. Every row must have the same number of elements.

Definition— The colon operator

first:last is the row vector first, first+1, … up to last. first:step:last uses another step, which may be negative or fractional: 10:-2:0 is 10 8 6 4 2 0. If the step overshoots, the range stops before last: 1:2:6 is 1 3 5.

The constructor functions are worth memorising. zeros(m, n) and ones(m, n) fill an m-by-n matrix; eye(n) is the identity matrix (Octave displays it as a special "Diagonal Matrix", but it behaves like any other); repmat(A, m, n) tiles copies of A; linspace(a, b, n) gives exactly n evenly spaced points from a to b, which is usually safer than a colon range with a fractional step; magic(n) is a magic square, handy for examples. rand(m, n) and randn(m, n) give random matrices; note that MATLAB and Octave generate different random numbers even with the same seed, so programs that print random values will not match between them.

With a single argument, zeros(3) is 3-by-3, not 1-by-3: a classic surprise. Write zeros(1, 3) for a row.

Worked examplesH

Reading elements: subscripts, end and the colon

matlab
A = reshape(1:12, 3, 4)
A(2, 3)
A(3, :)
A(:, end)
A(1:2, [1 4])
A(end, end)
A(5)
A(:)'
text
A =

    1    4    7   10
    2    5    8   11
    3    6    9   12

ans = 8
ans =

    3    6    9   12

ans =

   10
   11
   12

ans =

    1   10
    2   11

ans = 12
ans = 5
ans =

    1    2    3    4    5    6    7    8    9   10   11   12
  • A(row, col) picks one element. Rows come first, always.
  • Either subscript can be a vector: A(1:2, [1 4]) takes rows 1 and 2 of columns 1 and 4, giving a 2-by-2 block.
  • A bare : means "all": A(3, :) is the whole third row, A(:, 2) the whole second column.
  • end, inside an index, means the last index in that dimension, and it can take part in arithmetic: A(end-1, :) is the second-to-last row.

Linear indexing and column-major order

A(5) has only one subscript, and it returned 5. With a single subscript, MATLAB numbers the elements down the columns, the order in which they are actually stored in memory. This is column-major order, inherited from Fortran.

123456789101112storageorder
A 3-by-4 matrix and the linear index of each element: numbering runs down each column, then on to the next column.

reshape(1:12, 3, 4) fills a 3-by-4 matrix in exactly that order, which is why A holds the numbers 1 to 12 running down its columns. A(:) turns any array into one long column in linear order (here transposed with ' to print as a row). Column-major order explains several things you will meet: fprintf consumes matrices column by column, reshape and A(:) never move data, and loops that walk down columns are faster than loops that walk along rows.

Worked examplesH

Logical indexing and changing arrays

The most useful kind of index is a logical mask: an array of true and false values, the same size as the array, selecting the elements where it is true.

matlab
temps = [21 25 19 30 28 17 33];
hot = temps > 26
temps(hot)
find(hot)
temps(temps < 20) = 20
nnz(temps == 20)
temps(2) = []
temps(9) = 40
text
hot =

  0  0  0  1  1  0  1

ans =

   30   28   33

ans =

   4   5   7

temps =

   21   25   20   30   28   20   33

ans = 2
temps =

   21   20   30   28   20   33

temps =

   21   20   30   28   20   33    0    0   40
  • temps > 26 compares every element with 26 and returns a logical array of the same size.
  • temps(hot) keeps the elements where the mask is true. This one idea replaces most "loop, test, collect" code you would write in other languages.
  • find(hot) returns the positions of the true elements, here hours 4, 5 and 7.
  • A mask can appear on the left of an assignment: temps(temps < 20) = 20 raises every reading below 20 to 20. Here it changed two readings, as nnz (number of nonzeros) confirms.
  • Assigning the empty matrix deletes: temps(2) = [] removes the second element and shifts the rest left.
  • Assigning beyond the end grows the array, filling any gap with zeros: temps(9) = 40 added two zeros and then 40. Convenient, and a common source of silent bugs when an index is wrong.

Masks combine with & (and), | (or) and ~ (not): temps(temps > 20 & temps < 30) selects the comfortable hours. Use the double forms && and || only between single true/false values, as in if conditions.

Worked examplesH

Copies, concatenation and sizes

matlab
A = [1 2; 3 4];
B = A;
B(1, 1) = 100;
fprintf('A(1,1) is still %d\n', A(1, 1));

C = [A, A * 10]
D = [A; 5 6]
E = C';
fprintf('C is %dx%d, its transpose E is %dx%d\n', size(C), size(E));
fprintf('length(E) = %d, numel(E) = %d\n', length(E), numel(E));
G = zeros(2, 3, 4);
fprintf('G has %d dimensions and %d elements\n', ndims(G), numel(G));
text
A(1,1) is still 1
C =

    1    2   10   20
    3    4   30   40

D =

   1   2
   3   4
   5   6

C is 2x4, its transpose E is 4x2
length(E) = 4, numel(E) = 8
G has 3 dimensions and 24 elements
  • Assignment copies. B = A gives B its own copy (made lazily, only when one of them is changed), so changing B never changes A. Arrays have value semantics. This is a real difference from Python's NumPy, where b = a makes a second name for the same array, and a frequent surprise for people moving between the two.
  • Concatenation uses the same brackets as construction: [A, A * 10] places matrices side by side (they need the same number of rows) and [A; 5 6] stacks them (same number of columns).
  • ' transposes, swapping rows and columns. (For complex matrices ' also takes the complex conjugate; .' transposes without conjugating.)
  • Sizes. size gives every dimension; numel the total number of elements; ndims the number of dimensions. length gives the largest dimension, which is 4 for the 4-by-2 matrix E. Use numel to loop over all elements, and size(A, 1) or size(A, 2) for rows or columns; reach for length only with vectors.
  • Arrays can have more than two dimensions: zeros(2, 3, 4) is a stack of four 2-by-3 pages, as used for colour images (height by width by 3 colour channels) or time series of grids.
Worked examplesH

Worked example: a tiny image

Images are where indexing feels most natural, because a grayscale image simply is a matrix of brightness values, with rows running down the picture and columns across it. Here is a 5-by-6 "image" of a bright blob, small enough to read, and a handful of operations an image-processing routine might perform on it:

matlab
% A tiny 5-by-6 grayscale image: 0 is black, 9 is white.
img = [0 0 1 1 0 0
       0 3 8 9 2 0
       1 7 9 9 8 1
       0 2 9 8 3 0
       0 0 1 2 0 0];

centre = img(2:4, 2:5)
mirrored = img(:, end:-1:1);
disp(isequal(mirrored, fliplr(img)))

bright = img >= 7;
fprintf('%d bright pixels\n', nnz(bright));
[rows, cols] = find(bright);
disp([rows cols]')

[~, k] = max(img(:));
[r, c] = ind2sub(size(img), k);
fprintf('first brightest pixel: linear index %d = row %d, column %d\n', k, r, c);
fprintf('back again: %d\n', sub2ind(size(img), r, c));

img(~bright) = 0;
img
text
centre =

   3   8   9   2
   7   9   9   8
   2   9   8   3

1
8 bright pixels
   3   2   3   4   2   3   4   3
   2   3   3   3   4   4   4   5
first brightest pixel: linear index 13 = row 3, column 3
back again: 13
img =

   0   0   0   0   0   0
   0   0   8   9   0   0
   0   7   9   9   8   0
   0   0   9   8   0   0
   0   0   0   0   0   0

Line by line:

  • The matrix literal spans several lines; a line break inside brackets starts a new row, just like a semicolon. Laying data out this way makes it readable.
  • Cropping is plain block indexing: rows 2 to 4, columns 2 to 5.
  • Mirroring reverses the column order with the index end:-1:1. The built-in fliplr does the same (and flipud flips vertically); isequal confirms they agree, displaying 1 for true.
  • img >= 7 is a mask of bright pixels, and nnz counts them. With two outputs, find returns row and column subscripts instead of linear indices. Stacking them as columns and transposing prints one pixel per column: (3, 2), (2, 3), and so on, in column-major order.
  • max(img(:)) finds the largest value of the whole image; its second output is where it is, as a linear index. ind2sub converts a linear index to subscripts and sub2ind converts back. ~ in the output list discards an output you do not need.
  • Finally, img(~bright) = 0 blacks out everything that is not bright, a simple threshold, one of the first steps in many image-analysis pipelines.

Real images are bigger, of course, and usually stored as uint8 values from 0 to 255 in a height-by-width-by-3 array for colour, but every operation above works on them unchanged.

ExplanationH

How experienced users index

A few habits keep indexing code correct and fast.

Preallocate. Growing an array one element at a time inside a loop (result(end+1) = x) forces a new allocation and a copy at many steps, which becomes slow for large arrays. If you know the final size, create the array first with zeros(1, n) and fill it. Better still, compute the whole array at once with vectorised operations, the subject of the next lesson.

Be explicit about orientation. Many functions return rows, others columns, and combining a row with a column can silently produce a matrix (lesson 3 explains why). When a function should accept either, normalise at the start with x = x(:);, which makes any vector a column.

Prefer logical masks to find. x(x > 0) is clearer and usually faster than x(find(x > 0)). Use find when you need the positions themselves, or the first few matches: find(x > 0, 1) returns just the first.

Check sizes when something looks wrong. Most MATLAB bugs are shape bugs. When a result surprises you, print size of every array involved; the mistake is nearly always a row where a column was expected, or a dimension of 1 where you expected several.

Common misconceptionsH

Common misconceptions

Misconception

"length(A) is the number of rows." It is the largest dimension. For a 3-by-10 matrix it is 10. Use size(A, 1) for rows and numel(A) for the element count.

Misconception

"zeros(5) makes a vector of five zeros." With one argument, the constructor functions make a square matrix: 5-by-5, twenty-five zeros. Write zeros(1, 5) or zeros(5, 1).

Misconception

"A(2, 3) and A(3, 2) are the same element if I think in x and y." The first subscript is always the row (vertical position), the second the column. When working with images or grids, A(y, x) is the pattern; mixing this up transposes results without any error.

Misconception

"Assigning one array to another links them." Arrays are values; B = A makes an independent copy. (The exception is handle objects, an advanced feature of MATLAB's object system.)

Exercises

Exercises

1. Matrices, arrays and indexing

Warm-upComputational

What numbers does disp(10:-3:0) show? Write them separated by single spaces.

2. Matrices, arrays and indexing

Warm-upComputational

magic(4) is

16    2    3   13
 5   11   10    8
 9    7    6   12
 4   14   15    1

With A = magic(4), what is A(2, end)?

3. Matrices, arrays and indexing

StretchComputational

With B = reshape(1:20, 4, 5)'; (note the transpose), what is B(7)?

4. Matrices, arrays and indexing

CoreComputational

What does this display? Write the numbers separated by single spaces.

v = [4 -2 7 0 -5 3];
v(v < 0) = 0;
disp(v)

5. Matrices, arrays and indexing

Warm-upComputational

What is numel(find([3 8 1 9 4] > 3))?

6. Matrices, arrays and indexing

CoreComputational

What does this display?

x = 1:5;
x(8) = 1;
disp(sum(x))

7. Matrices, arrays and indexing

CoreHuman

M = zeros(3, 10); Which expression gives the number of rows of M?

Choose one

Further reading and resources