Tutorial

How to Create Numeric Sequences Using the Colon Operator in MATLAB

The colon operator creates numeric sequences via the syntax start:step:end.

Syntax

The syntax 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;

Examples

The colon operator creates increasing or decreasing sequences. To create a decreasing sequence, specify a negative value for step. If start:step:end does not make sense, the result is an empty matrix.

% Even numbers from 0 to 10
resultExample1 = 0:2:10;
% Integers from 0 to -5
resultExample2 = 0:-1:-5;
% Values from 1 to 2, spaced by 0.25 units
resultExample3 = 1:0.25:2;
% Bad input
wrongExample = 1:3:-5;

Further reading

I recommend the following books to learn more on the colon operator in MATLAB:

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a 2017 Textbook Excellence Award. The colon operator is explained clearly in the second chapter.

  2. 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.

doc :;

Exercise

Create the following numeric sequences using the colon operator:

  1. Odd numbers from 2 to 12
  2. Numbers multiple of 4 in the interval \([3,25]\)
  3. \(\{−1,−1.5,−2,−2.5,−3,…,-6\}\)

Source code

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.

Share

Your friends may need this knowledge to complete a task. Share this tutorial.