tags:

views:

43

answers:

2

I am new to using MATLAB, and I came across some syntax about colon that I don't fully understand.

First Question:

The expression: 0:pi/4:pi results in the answer: 0 0.7854 1.5708 2.3562 3.1416

Why is this the case? I thought that colon operator is used as a quick way to refer to indices so that we don't have to write out the full list. (e.g. 1:3 -> 1 2 3)

Second Question:

Similar to above, say if I have a matrix X = [1 2 3 4 5 6 7 8 9]. How can I interpret the expression X(:,1:3)? Specifically, what does the colon operator without the left and right numbers mean?

Thanks a lot.

+1  A: 

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.

KennyTM
Thank you very much.
thomas1234
@KennyTM: Remember that `a:b:c` is not always the same as `[a a+b a+b+b .. c]`; try this example: `x=0; for i=1:10, x=x+0.1; end` then if you compare `x==1` it will return false, due to accumulated floating-point inaccuracies (in fact `abs(x-1)` is something to the order of `1e-16`)
Amro
@Amro: I don't think your for loop has anything to do with the `a:b:c` syntax.
KennyTM
@KennyTM: Well if you want to be exact, then compare `y = 0:0.1:1;` to the for-loop: `x(1)=0; for i=1:10, x(i+1)=x(i)+0.1; end`, and you will see that `all(x==y)` is not always true
Amro
@Amro: Right, but `a:b:c` is constructed using http://www.mathworks.com/support/solutions/en/data/1-4FLI96/index.html?solution=1-4FLI96
KennyTM
@KennyTM: that's exactly the point I'm trying to make: the colon operator in this case does not do repeated additions, rather it is careful to arrange that the last element is exactly the end number..
Amro
@Amro: OK I see.
KennyTM
@KennyTM: thanks for the link BTW :)
Amro
+1  A: 

My two pennies to KennyTM's answer.

Actually scalar and vector variables in MATLAB have 2 dimensions. Scalar has 1 row and 1 column, and vector has either 1 row or column. Just try size(X).

Colon (:) operator for indexing simply means all. Syntax X(:,1:3) means get all rows and columns from 1 to 3. Since your variable X has only 1 row, you will get first 3 values in this row.

yuk

related questions