Skip to Main Content Skip to Search
Product Documentation

colon (:) - Create vectors, array subscripting, and for-loop iterators

Description

The colon is one of the most useful operators in MATLAB. It can create vectors, subscript arrays, and specify for iterations.

The colon operator uses the following rules to create regularly spaced vectors for scalar values i, j, and k:

j:k

is the same as [j,j+1,...,k], or empty when j > k.

j:i:k

is the same as [j,j+i,j+2i, ...,j+m*i], where m = fix((k-j)/i), for integer values. For information on the definition of j:i:k with floating-point values, see Technical Solution 1-4FLI96. This syntax returns an empty matrix when i == 0, i > 0 and j > k, or i < 0 and j < k.

If you specify nonscalar arrays, MATLAB interprets j:i:k as j(1):i(1):k(1).

You can use the colon to create a vector of indices to select rows, columns, or elements of arrays, where:

A(:,j)

is the jth column of A.

A(i,:)

is the ith row of A.

A(:,:)

is the equivalent two-dimensional array. For matrices this is the same as A.

A(j:k)

is A(j), A(j+1),...,A(k).

A(:,j:k)

is A(:,j), A(:,j+1),...,A(:,k).

A(:,:,k)

is the kth page of three-dimensional array A.

A(i,j,k,:)

is a vector in four-dimensional array A. The vector includes A(i,j,k,1), A(i,j,k,2), A(i,j,k,3), and so on.

A(:)

is all the elements of A, regarded as a single column. On the left side of an assignment statement, A(:) fills A, preserving its shape from before. In this case, the right side must contain the same number of elements as A.

When you create a vector to index into a cell array or structure array (such as cellName{:} or structName(:).fieldName), MATLAB returns multiple outputs in a comma-separated list. For more information, see How to Use the Comma-Separated Lists in the MATLAB Programming Fundamentals documentation.

Examples

Using the colon with integers,

D = 1:4

results in

D =
    1    2    3    4
 

Using two colons to create a vector with arbitrary real increments between the elements,

E = 0:.1:.5

results in

E =
    0    0.1000    0.2000    0.3000    0.4000    0.5000
 

The command

A(:,:,2) = pascal(3)

generates a three-dimensional array whose first page is all zeros.

A(:,:,1) =
     0     0     0
     0     0     0
     0     0     0

A(:,:,2) =
     1     1     1
     1     2     3
     1     3     6
 

Using a colon with characters to iterate a for-loop,

for x='a':'d',x,end

results in

x = 
    a
x = 
    b
x = 
    c
x = 
    d

See Also

for | linspace | logspace | reshape | varargin

  


Free MATLAB Interactive Kit

Explore how to use MATLAB to make advancements in engineering and science.


Download free kit

Trials Available

Try the latest version of MATLAB and other MathWorks products.


Get trial software
 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS