Colon operator in Matlab

Colon operator (:) is one of the most important MATLAB operators. It is found in many different forms. For example, the following expression:

1:10

represents a row vector that contains integers from 1 to 10

1 2 3 4 5 6 7 8 9 10

To obtain a specific sequence instead, an increase must be indicated. For example:

>> 100: -7: 50

ans =

100 93 86 79 72 65 58 51

that is, a sequence of numbers from 100 to 50 with a step equal to -7; while

>> 0: pi / 4: pi

ans =

0 0.7854 1.5708 2.3562 3.1416

Colon operator in Matlab

The subscribed expressions involving the operator two points assign portions of a matrix. For example, we assign the usual matrix:

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

and let’s extract some values:

A (1: k, j)

represents the first k elements of the jth column of A. Then we extract some elements:

>> A (1: 4.4)

ans =

4
8
12
16

and we calculate the sum of the fourth column.

>> sum (A (1: 4.4))

ans =

40

The colon assigns all the elements in a row or column of a matrix and the keyword END assigns the last row or column. So

>> sum (A (:, end))

ans =

40

calculates the sum of the elements in the last column of A.

Leave a Reply

Your email address will not be published. Required fields are marked *