start:step:end creates a sequence of numbers that begin at
start, are spaced by
step units, and are not greater (or lower if \(step < 0\)) than
end. The parameter
step is optional and its default value is 1.
% Integers from 1 to 5 R = 1:5;
R = 1 2 3 4 5
The colon operator creates increasing or decreasing sequences. To create a decreasing sequence, specify a negative value for
start:step:end does not make sense, the result is an empty matrix.
% Even numbers from 0 to 10 resultExample1 = 0:2:10;
resultExample1 = 0 2 4 6 8 10
% Integers from 0 to -5 resultExample2 = 0:-1:-5;
resultExample2 = 0 -1 -2 -3 -4 -5
% Values from 1 to 2, spaced by 0.25 units resultExample3 = 1:0.25:2;
resultExample3 = 1.0000 1.2500 1.5000 1.7500 2.0000
% Bad input wrongExample = 1:3:-5;
wrongExample = Empty matrix: 1-by-0
I recommend the following books to learn more on the colon operator in MATLAB:
This book was the winner of a Textbook Excellence Award. The colon operator is explained clearly in the second chapter.
MATLAB for Engineers (5th Edition)
This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. The fourth chapter is completely dedicated to matrix manipulation.
I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series, but especially this tutorial.
- MATLAB Concatenation Operator Explained
- How to Create Numeric Sequences Using the Colon Operator in MATLAB
- MATLAB Colon Operator in Matrix Indexing Expressions
- Multiline Statements in MATLAB
Create the following numeric sequences using the colon operator:
- Odd numbers from 2 to 12
- Numbers multiple of 4 in the interval \([3,25]\)
A possible solution could be:
% Clause 1 resultClause1 = 3:2:12; % Clause 2 resultClause2 = 4:4:25; % Clause 3 resultClause3 = -1:-0.5:-6;
I hope you have learned how to create numeric sequences using the colon operator. The source code developed in this tutorial is available at this page.