TExcelTAD
Home › MATLAB / Octave › Indexing

Indexing

Indexing means reading or changing parts of an array. MATLAB uses parentheses and counts from 1, not 0: the first element of v is v(1).

Vector indexing

matlab · try it yourself
v = [10 20 30 40 50];
disp(v(1))
disp(v(end))          % end means "the last index"
disp(v(end-1))
disp(v([1 3 5]))      % several indices at once
disp(v(2:4))          % a range
disp(v(end:-1:1))     % reversed
10
50
40
   10   30   50
   20   30   40
   50   40   30   20   10

Inside an index, end stands for the length along that dimension, so v(end) always gets the last element whatever the size.

Matrix indexing: row, column

For a matrix, give the row first, then the column: A(r, c). A colon on its own means "all rows" or "all columns":

matlab · try it yourself
A = [1 2 3; 4 5 6; 7 8 9];
disp(A(2, 3))        % row 2, column 3
disp(A(3, :))        % the whole third row
disp(A(:, 1))        % the whole first column
disp(A(1:2, 2:3))    % a 2x2 block
disp(A(end, end))
6
   7   8   9
   1
   4
   7
   2   3
   5   6
9

Linear indexing

You can also index a matrix with a single number. MATLAB stores matrices column by column, and a single index counts through them in that order:

matlab · try it yourself
A = [1 2 3; 4 5 6; 7 8 9];
disp(A(2))           % second element going down column 1
disp(A(4))           % first element of column 2
disp(A(:)')          % all elements in storage order
idx = sub2ind(size(A), 3, 2);
fprintf('row 3, col 2 is linear index %d\n', idx);
[r, c] = ind2sub(size(A), 8);
fprintf('linear index 8 is row %d, col %d\n', r, c);
4
2
   1   4   7   2   5   8   3   6   9
row 3, col 2 is linear index 6
linear index 8 is row 2, col 3

sub2ind and ind2sub convert between the two styles.

Changing elements

An indexed expression on the left of = changes just those elements. Assigning a scalar to a range sets every element in it:

matlab · try it yourself
v = [10 20 30 40 50];
v(2) = 99;
v([4 5]) = 0;
disp(v)

A = zeros(3);
A(2, :) = [1 2 3];     % replace a row
A(:, 3) = 7;           % set a whole column
disp(A)
   10   99   30    0    0
   0   0   7
   1   2   7
   0   0   7

Growing and deleting

Assigning beyond the end grows the array and fills any gap with zeros. Assigning the empty matrix [] deletes elements, rows or columns:

matlab · try it yourself
v = [1 2 3];
v(6) = 6;
disp(v)
v([2 4]) = [];
disp(v)

M = magic(4);
M(:, 2) = [];          % delete column 2
M(1, :) = [];          % delete row 1
disp(M)
   1   2   3   0   0   6
   1   3   0   6
    5   10    8
    9    6   12
    4   15    1

Index errors

Reading past the end, or using 0 or a fraction as an index, is an error. The exact message differs between MATLAB and Octave, so catch errors and print err.message only while learning:

matlab · try it yourself
v = [1 2 3];
try
    x = v(5);
catch err
    disp('Reading v(5) failed:')
    disp(err.message)
end
try
    x = v(0);
catch err
    disp('Reading v(0) failed too.')
end
Reading v(5) failed:
v(5): out of bound 3 (dimensions are 1x3)
Reading v(0) failed too.

MATLAB's wording for the first error is "Index exceeds the number of array elements. Index must not exceed 3."

Test yourself

For v = [5 6 7 8], what is v(end-1)?

  1. 6
  2. 7
  3. 8
  4. An error

What does A(:, 2) select?

  1. Row 2
  2. Column 2
  3. The element at linear index 2
  4. Every second element

For A = [1 2; 3 4], what is A(2)?

  1. 2
  2. 3
  3. 4
  4. [3 4]