The meaning of colon operator in MATLAB

Actually a:b generates a vector. You could use it as index only because the (...) accepts a list also, e.g.

octave-3.0.3:10> a = [1,4,7]
a =

   1   4   7

octave-3.0.3:11> b = [1,4,9,16,25,36,49]
b =

    1    4    9   16   25   36   49

octave-3.0.3:12> b(a)    # gets [b(1), b(4), b(7)]
ans =

    1   16   49

Now, the a:b:c syntax is equivalent to [a, a+b, a+2*b, ...] until c, e.g.

octave-3.0.3:15> 4:7:50
ans =

   4  11  18  25  32  39  46

which explains what you get in 0:pi/4:pi.


A lone : selects the whole axes (row/column), e.g.

octave-3.0.3:16> a = [1,2,3;4,5,6;7,8,9]
a =

   1   2   3
   4   5   6
   7   8   9

octave-3.0.3:17> a(:,1)   # means a(1:3, 1)
ans =

   1
   4
   7

octave-3.0.3:18> a(1,:)   # means a(1, 1:3)
ans =

   1   2   3

See the official MATLAB doc on colon (:) for detail.

Leave a Comment