# Access to elements of an array in Matlab

In this post, we see how to access the elements of an array in the Matlab environment; first of all, then insert a sample matrix in the Matlab workspace:

>> A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]

A =

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

The element in line i and column j of A is denoted with the symbol A (i, j). Eg:

>> A (4.2)

ans =

14

is the number in the fourth row and second column. For our matrix it corresponds to 14. Thus it is possible to calculate the sum of the elements in the fourth column of A by typing:

A (1,4) + A (2,4) + A (3,4) + A (4,4)

This produces:

>> A (1,4) + A (2,4) + A (3,4) + A (4,4)

ans =

40

but it is not the most elegant way to add a single column. It is also possible to access the elements of a matrix using a single subscript, A (k). This is the usual way to access the elements of row vectors and column vectors.

Access to elements of an array in Matlab

But it can also be applied to a two-dimensional array in this case the matrix is â€‹â€‹considered as a column vector, formed by the columns of the original matrix. Thus, for our matrix, A (8) is another way of identifying the value 14 stored in position A (4.2), ie fourth row second column.

>> A (8)

ans =

14

If you try to access the elements of an array outside it, you make a mistake:

>> t = A (4,5)
??? Attempted to access A (4.5); index out of bounds because size (A) = [4.4].

(Error message)

On the other hand, if we store a new value in an element of the matrix that exceeds its order, there is an increase in order to accommodate the newcomer:

>> A (4.5) = 17

A =

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

The carriers are treated in Matlab in a completely similar way. You can view the individual entries of a vector, after having defined it as follows:

V = [2 1 3 4];

to view the first item, simply type:

>> V (1)
ans =
2

This command prints the first element in the vector. Also note that a new variable called ans was created.