8.8: The Colon
- Page ID
- 10161
You can use the colon several ways in MATLAB (see help :). Its basic meaning is a vector of sequential values. For example, type
≫ x = 3:9
to get
x = 3 4 5 6 7 8 9
For increments other than 1, use statements like
≫ x = 1:0.5:4 ≫ x = 6:-1:0
Most MATLAB functions will accept vector inputs and produce vector outputs. The statement
≫ y = sqrt(1:10)
builds a vector of integers from 1 to 10 and takes the square root of each of those numbers. Try it.
Now for another subtlety–what is the effect of each of the following statements and why?
≫ 1+1:5 ≫ 1+(1:5)
Appending to a Matrix or Vector
A matrix or vector can be enlarged in size by appending new values to the old values. Let x=[1 3 5]
:
\[\mathrm{x}=[\mathrm{x} 6810] \Rightarrow \mathrm{x}= [1356810] \nonumber \]
\[y=[x ; 1: 6] \Rightarrow y=\left[\begin{array}{llllll}
1 & 3 & 5 & 6 & 8 & 10 \\
1 & 2 & 3 & 4 & 5 & 6
\end{array}\right] \nonumber \]