Octave – Indexes, Vector Indexes and Range Indexes

Indexes allows you to access an elements from a matrix or vector (think about accessing data in a multidimensional Array)

The indexing operator is (), so to access data in Row 2; Column 3 you would do


You are also able to assing a new value to that index


Supplying just one index returns a scalar result.

A(1:2)     # Vector result
A([1:2])   # Column Vector result

You can also use the colon for a column vector output containing all the elements


Given the follow

a = [1, 2; 3, 4]

all of the following expression are equivalent and select the first row of the matrix

a(1, [1, 2])    # row 1, columns 1 and 2
a(1, 1:2)       # row 1, columns in range 1 - 2
a(1, : )         # row 1, all columns

When you have large data sets and you need to select, say, the first 1000 elements in column 1 you would do

A(1:1000, 1)

You could also do the following, so that the range can be interpreted as a row vector


If you wanted to select every other row, you would do


And if you wanted to pick out the first 1000 rows and the 1500th row


In index expressions the keyword end automatically refers to the last entry for a particular dimension. This magic index can also be used in ranges and typically eliminates the needs to call size or length to gather array bounds before indexing.

a = [1, 2, 3, 4];

a(1:end/2)        # first half of a => [1, 2]
a(end + 1) = 5;   # append element
a(end) = [];      # delete element
a(1:2:end)        # odd elements of a => [1, 3]
a(2:2:end)        # even elements of a => [2, 4]
a(end:-1:1)       # reversal of a => [4, 3, 2 , 1]