Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 45 ยท Matrices and Arrays

Indexing and Slicing

Pick elements, rows, columns and blocks from MATLAB and Octave arrays with subscripts, the colon, end, linear indexing, sub2ind, deletion and growth.

Creating a matrix is only half the job. Almost every program also reads a piece of one: the third row, the last column, every other element, a block in the corner. MATLAB and Octave handle all of these with the same notation, A(rows, columns), where each part can be a number, a list of numbers or a colon meaning "all".

This lesson covers subscripts and ranges, the colon and end, linear indexing and the conversion functions sub2ind and ind2sub, deleting elements and growing arrays, and the off-by-one differences you must handle when translating to Python. The MATLAB blocks are read-only; Python stand-ins let you check the results.

All examples below use this 4-by-4 matrix, which is what magic(4) returns:

MATLAB
>> A = magic(4)
A =

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

Subscripts

Give the row first and the column second. Each can be a single number or a vector of numbers:

MATLAB
>> A(2, 3)              % one element
ans =
    10
>> A(2, [1 4])          % row 2, columns 1 and 4
ans =
     5     8
>> A([1 3], [2 3])      % rows 1 and 3, columns 2 and 3
ans =

     2     3
     7     6

A vector of numbers in an index picks those positions in that order, repeats included, so A(1, [4 4 1]) returns 13 13 16.

The colon and end

A lone colon means "every index along this dimension". A range such as 2:3 picks consecutive positions, and the end point is included:

MATLAB
>> A(2, :)              % all of row 2
ans =
     5    11    10     8
>> A(:, 1)              % all of column 1, as a column vector
ans =
    16
     5
     9
     4
>> A(2:3, 2:3)          % the block in the middle
ans =

    11    10
     7     6

The keyword end stands for the last index in whichever position it appears, so you never need to know the size. It works inside arithmetic too:

MATLAB
>> A(end, end)          % bottom-right element
ans =
     1
>> A(end, :)            % last row
ans =
     4    14    15     1
>> A(1:2:end, :)        % every other row, starting at the first
ans =

    16     2     3    13
     9     7     6    12

Range steps work in indexes: v(end:-1:1) reverses a vector. The same trick 1:2:end is how you take every second element.

Tip: Slices of MATLAB arrays are always copies that you may change freely. In NumPy a basic slice is a view of the same data, so changing it changes the original unless you call .copy().

The stand-in below reads the same pieces from the same matrix. Notice what changes in NumPy: indexes start at 0, a slice a:b stops before b, and end becomes -1 or an omitted bound.

Python The same slices in NumPy (stand-in)

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 translation rule for ranges is easy to remember. A MATLAB range a:b (1-based, inclusive) becomes the NumPy slice a-1:b (0-based, exclusive end). The end index stays the same number, because moving the start down by one and the end up by one cancel out.

Linear indexing

You can index a matrix with a single number. MATLAB numbers the elements down the columns, starting at the top-left: first column top to bottom, then the second column, and so on.

MATLAB
>> A(5)                 % first element of column 2
ans =
     2
>> A([1 6 11 16])       % the main diagonal
ans =
    16    11     6     1
>> A(1:8)'              % the first eight elements as a row
ans =

    16     5     9     4     2    11     7    14

A(:) is a handy idiom that turns any array into a single column. It is also the way to apply a function to all elements and get one list back.

To translate between the two forms there are sub2ind and ind2sub. For a 4-by-4 matrix, row 2 and column 3 has the linear index (3 - 1) * 4 + 2 = 10:

MATLAB
>> idx = sub2ind([4 4], 2, 3)
idx =
    10
>> [r, c] = ind2sub([4 4], 10)
r =
     2
c =
     3

You see linear indexes in the output of find and max for matrices, which is why the conversion functions matter.

NumPy stores rows contiguously, so to follow MATLAB's order you must ask for column-major ("Fortran") order explicitly. The functions np.ravel_multi_index and np.unravel_index accept order="F".

Python Linear indexes, sub2ind and ind2sub (stand-in)

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.

Assigning through an index

The same notation works on the left side of =. The right side must be a scalar (which fills every selected position) or have the same number of elements as the selection:

MATLAB
>> A(1, :) = 0          % zero the first row
>> A(:, 2) = [1; 2; 3; 4]
>> A(2:3, 2:3) = [100 200; 300 400]

If the sizes do not match, MATLAB reports an error that says the left and right sides have different numbers of elements. Fixing it is nearly always a matter of counting rows and columns of both sides.

Deleting elements

Assign the empty matrix [] to remove elements. You can remove entire rows or columns, but you cannot remove a single element from the middle of a matrix because the result would no longer be rectangular.

MATLAB
>> v = [10 20 30 40 50];
>> v(2) = [];           % v is now 10 30 40 50
>> A(:, 2) = [];        % remove column 2, A becomes 4x3
>> A([1 4], :) = [];    % remove rows 1 and 4, A becomes 2x3

Growing arrays

Writing to an index past the end enlarges the array. Missing positions are filled with zeros:

MATLAB
>> v = [1 2 3];
>> v(6) = 9
v =

     1     2     3     0     0     9
>> w = [];
>> w(end + 1) = 5;      % append
>> w(end + 1) = 7       % w is now 5 7

Growing like this is convenient for experiments, but each growth may copy the whole array. Inside a big loop, preallocate with zeros instead; see Performance and Memory.

NumPy arrays have a fixed size, so deleting and growing create new arrays with np.delete and np.append. The stand-in imitates the MATLAB behaviours:

Python Delete and grow (stand-in)

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.

Off-by-one cheat sheet

Task MATLAB / Octave NumPy
First element v(1) v[0]
Last element v(end) v[-1]
Elements 2 to 4 v(2:4) v[1:4]
Every other, from first v(1:2:end) v[::2]
Row 3 A(3, :) A[2, :]
Reverse v(end:-1:1) v[::-1]

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. For A = magic(4) shown above, what does A(2:3, 2:3) return?

    2:3 selects rows 2 and 3, and the second 2:3 selects columns 2 and 3, giving a 2-by-2 block.
  2. 2. What does v(end:-1:1) do?

    The range starts at the last index and counts down by 1 to the first, so every element appears in reverse.
  3. 3. In which order does a linear index number the elements of a matrix?

    MATLAB stores matrices column by column, so linear index 1 to 4 in a 4-by-4 matrix is the first column from top to bottom.
  4. 4. Which statement removes the second column of A?

    A(:, 2) selects the whole second column, and assigning [] to it deletes it. A(2, :) = [] would delete the second row.
  5. 5. The MATLAB expression A(2:4) on a vector corresponds to which NumPy expression?

    Shift the start down by one for zero-based counting and keep the end, because NumPy slices exclude their end: positions 2, 3 and 4 become zero-based 1, 2 and 3, written 1:4.

Summary

  • A(rows, cols) takes each part as a number, a vector of numbers, a range or a colon for "all".
  • Ranges like 2:3 are inclusive; end is the last index and works in arithmetic and ranges.
  • A single index counts down the columns (linear indexing); sub2ind and ind2sub convert between forms.
  • Assigning [] deletes whole rows or columns; writing past the end grows the array and pads with zeros.
  • Translating to NumPy means subtracting 1 from starts and remembering that slices exclude their end.

Next, choose elements by condition instead of position in Logical Indexing and find.