17
votes

We all know the matlab colon operator to create a linear sequence, i.e.

1:5 = [1 2 3 4 5]

Now I found that the arguments of the colon operator can also be applied to vectors or matrices. However I do not understand the definition behind.

Examples

[1 2 3 4]:5 == [1 2 3 4 5]

[1 2; 3 4]:3 == [1 2 3]

Why is this?

The second argument can be vector or matrix as well.

Ultimately I would like to understand sequences such as

1:2:3:4:5 

which is fully legal in matlab and [1 5] by the way!

Note 1:2:3:4:5:6 is left associative i.e. parsed as ((1:2:3):4:5):6.

So what is the behavior for the colon operator with matrix/vector arguments?

EDIT: corrected the statement of left associativity.

1
In my experience (I haven't searched the documentation), [a b c]:[d e; f g] is equivalent to a:d. That is, the colon picks the first element of each vector or matrixLuis Mendo
@LuisMendo: Yes, I can experimentally confirm. I didn't find it in the documentation.Jonas

1 Answers

15
votes

The documentation for the colon operator says:

If you specify nonscalar arrays, MATLAB interprets j:i:k as j(1):i(1):k(1).

Your first example is interpreted as 1:3, the second as 1:5

Expressions with more than two : are parsed left-associative:

a:b:c:d:e==(a:b:c):d:e

.

    >> 1:2:3:4:5

ans =

     1     5