Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

behavior of colon operator (:) with matrix or vector arguments

Tags:

matlab

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.

like image 955
Andreas H. Avatar asked Mar 27 '15 09:03

Andreas H.


People also ask

What does the colon do in MATLAB matrix?

The colon is one of the most useful operators in MATLAB®. It can create vectors, subscript arrays, and specify for iterations. x = j : k creates a unit-spaced vector x with elements [j,j+1,j+2,...,j+m] where m = fix(k-j) . If j and k are both integers, then this is simply [j,j+1,...,k] .

What does colon mean in vectors?

The symbol colon ( : ) is used as an operator in MATLAB programming and is a commonly used operator. This operator is used to construct a vector that is defined by a simple expression, iterate over or subscribe to an array, or access a set of elements of an existing vector.

What does colon operator refers to in R?

Colon operator (":") in R is a function that generates regular sequences. It is most commonly used in for loops, to index and to create a vector with increasing or decreasing sequence.

What is a colon operator?

The colon operator, :, makes sequences of integers. For example, 4:7 creates the vector 〈4, 5, 6, 7〉. The combine function and the colon operator are used very often in R programming. The colon operator has precedence over basic arithmetical operators, but not over the power operator.


1 Answers

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
like image 108
Daniel Avatar answered Oct 14 '22 04:10

Daniel