Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
824 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...