Programming Previous page   Next Page

Generating a Numeric Sequence

Because numeric sequences can often be useful in constructing and indexing into matrices and arrays, MATLAB provides a special operator to assist in creating them.

This section covers

The Colon Operator

The colon operator (first:last) generates a 1-by-n matrix (or vector) of sequential numbers from the first value to the last. The default sequence is made up of incremental values, each 1 greater than the previous one:

The numeric sequence does not have to be made up of positive integers. It can include negative numbers and fractional numbers as well:

By default, MATLAB always increments by exactly 1 when creating the sequence, even if the ending value is not an integral distance from the start:

Also, the default series generated by the colon operator always increments rather than decrementing. The operation shown in this example attempts to increment from 9 to 1 and thus MATLAB returns an empty matrix:

The next section explains how to generate a nondefault numeric series.

Using the Colon Operator with a Step Value

To generate a series that does not use the default of incrementing by 1, specify an additional value with the colon operator (first:step:last). In between the starting and ending value is a step value that tells MATLAB how much to increment (or decrement, if step is negative) between each number it generates.

To generate a series of numbers from 10 to 50, incrementing by 5, use

You can increment by noninteger values. This example increments by 0.2:

To create a sequence with a decrementing interval, specify a negative step value:


Previous page  Matrix Concatenation Functions Combining Unlike Data Types Next page

© 1994-2005 The MathWorks, Inc.