lettura simple

How do you access elements of an array in octave?

In this lesson I'll explain how to get an element of an array in Octave by a practical example.

Create an array with multiple values.

>> v=['a', 'b', 'c', 'd']

It is an array with only one dimension.

Note. Arrays have a dimension (1D) if its values are arranged in a single row or in a single column. In practice, one-dimensional arrays are vectors. $$ v = \begin{pmatrix} a & b & c & d \end{pmatrix} $$ $$ v = \begin{pmatrix} a \\ b \\ c \\ d \end{pmatrix} $$

To access the first element of the array, type the name of the array and the position of the element in brackets.

For example, to access the first element of the array, type v(1).

>> v(1)
ans = a

Note. Unlike many programming languages, the first element of an array has the index equal to one in Octave. In programming languages such as Python or Java, however, the first element of the arrays has a zero index.

To access the second element of the array, type v(2)

>> v(2)
ans = b

You can also change the value of an element.

For example, to change the value of the second element type v(2)='x'

>> v(2)='x'

Now the elements of the array are

>> v
ans = a, x, d, e

How to access the elements of an array?

If the array has two dimensions, to access an element you must specify the row and column number (r, c) of the element.

For example, create a 2x2 matrix with two rows and two columns.

>> m=['a', 'b'; 'c', 'd']

It is a square matrix

$$ \begin{pmatrix} a & b \\ c & d \end{pmatrix} $$

Note. To represent a matrix on Octave you need to use a two dimensional (2D) array. Two-dimensional arrays have two indices (r, c), one index to indicate the row number (r) and another index to indicate the column number (c). The two indices must be separated by a comma.Per accedere al primo elemento dell'array digita il nome dell'array e la posizione (riga,colonna) dell'elemento tra parentesi

For example, to read the element on the first row and first column of the array, type m(1,1)

>> m(1,1)
ans = a

If you want to read the element on the first row and second column, type m(1,2)

>> m(1,2)
ans = b

To read the second item on the second line, type m(2,2)

>> m(2,2)
ans = d

Report a mistake or post a question