Colon notation is a powerful shorthand for creating vectors. It is especially helpful when used to create ranges of subscripts to select parts of vectors or matrices.
Creating vectors
The MATLAB colon operator can be used to create vectors. The vector to be created can be specified by either two parameters or three parameters.
The two parameter form is
x = v1:v2
which creates a vector with a starting value of v1
and an ending value of v2
with integer values in between.
>> x = 1:5
x =
1 2 3 4 5
>> z = -3:3
z =
-3 -2 -1 0 1 2 3
The three-parameter form allows the increment between vector elements to be specified.
x = v1:inc:v2
The preceding statement creates a vector starting with v1
, subsequent elements
incremented by inc
, and stopping at or before v2
.
>> s = 0:2:10
s =
0 2 4 6 8 10
>> t = 10:-1:0
t =
10 9 8 7 6 5 4 3 2 1 0
The increment does not need to be an integer.
>> r = 0:0.3:1
r =
0 0.3000 0.6000 0.9000
>> w = 1:(3/5):5
w =
1.0000 1.6000 2.2000 2.8000 3.4000 4.0000 4.6000
Note that unlike the linspace
command, the ending value is not necessarily included
in the list of values.
Vectors of subscripts
The colon operator is a convenient and powerful way to create vectors of subscripts, which allow selection of subsets of elements in vectors or matrices.
>> A = magic(5)
A =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
>> A(1:2, 3:4)
ans =
1 8
7 14
>> A(1:2, 1:3)
ans =
17 24 1
23 5 7
Taking the vector of subscripts idea to the extreme, the colon can be used as a wildcard to refer to an entire row or column.
>> A = magic(5);
>> A(1,:)
ans =
17 24 1 8 15
>> A(:,3)
ans =
1
7
13
19
25
Special trick: Converting matrices and vectors to column vectors
The transpose operator converts a column vector to a row vector, and a row vector to a column vector. Sometimes, you want to make sure that a vector is a column vector. In that situation, there is a special trick with the colon operator.
x = ... % x is a row or column vector
y = x(:) % y is a column vector formed from the elements of x
Here are some concrete examples
>> r = 1:4
r =
1 2 3 4
>> s = r(:)
s =
1
2
3
4
>> t = (1:4)'
t =
1
2
3
4
>> u = t(:)
u =
1
2
3
4
This trick also works on matrices by stacking the columns into a single column.
>> A = [1 5; 2 6; 3 7; 4 8]
A =
1 5
2 6
3 7
4 8
>> b = A(:)
b =
1
2
3
4
5
6
7
8