The colon operator
Frequently you want to create vectors whose elements are defined by a simple expression or to access a sequence of elements in a vector. The colon operator : provides a very convenient way of doing this.
In its simplest form a:b starts at a, then increases in steps of 1, until b is reached.
In this case the square brackets are not required to create a row vector.
A slightly more general form of the colon operator is a:step:b, which starts at a, then adds step repeatedly, until b is reached (or exceeded).
If step > 0, then a should be less than or equal to b, and the final number is less than or equal to b.
This produces 5, 7, 9, 11.
In fact the value of step does not have to be an integer. It can even be negative, in which case a should be greater than b.
The vector z has 21 elements 1, 1.05, 1.1, 1.15, ... 1.95, 2.
The vector z has 21 elements 1, 1.05, 1.1, 1.15, ... 1.95, 2.
The vector zr has 21 elements 2, 1.95, 1.90, 1.85, ... 1.05, 1.
The linspace command
The task of creating a vector of equally (or linearly) spaced points between two limits occurs so commonly that MATLAB has a special command linspace to do this. The command linspace(a, b, n) creates n equally spaced points between a and b, including both a and b.
As both end points are included, this produces the vector with elements 1.0000 1.1111 1.2222 1.3333 1.4444 1.5556 1.6667 1.7778 1.8889 2.0000.
If you wanted points with a spacing of 0.1, and including both end points, then you need a total of 11 points.
Indexing vectors
The colon operator is very helpful for indexing elements of a vector.
1:4 gives 1, 2, 3, 4, so you get the values of the first 4 elements of z2.
7:2:11 gives 7, 9, 11, so you get the values of these elements of z2.
The MATLAB keyword end is used for several purposes. When referring to an element of a vector, it refers to the last element.
end-2:end gives you elements 9, 10 and 11 of z2 as z2 has 11 elements.
Warnings
- What happens with x = 3:1?
- Remember to use semi-colons ; to suppress unwanted output.
Self-test Exercise
Use the colon operator to:
- Create a vector u with elements uk = k, k = 1,...,12.
- Create a vector v consisting of elements 1, 4, 7, 10 of u.
Answer:
- u = 1:12
- v = u([1:3:10])
Summary
Equally spaced points can be created either by using the colon operator : or the linspace command
The colon operator is useful both for efficiently creating a new vector and for accessing selected elements of an already existing vector.