colon, :
Vector creation, array subscripting, and for-loop
iteration
Syntax
x = j:k x = j:i:k A(:,n) A(m,:) A(:) A(j:k)
Description
The colon is one of the most useful operators in MATLAB®. It can create vectors, subscript arrays, and specify
for iterations.
creates a regularly-spaced vector x = j:i:kx using
i as the increment between elements. The vector elements
are roughly equal to [j,j+i,j+2*i,...,j+m*i] where m
= fix((k-j)/i). However, if i is not an
integer, then floating point arithmetic plays a role in determining whether
colon includes the endpoint k in the
vector, since k might not be exactly
equal to j+m*i.
x = colon(j,k) and x = colon(j,i,k)
are alternate ways to execute the commands j:k and
j:i:k, but are rarely used. These syntaxes enable
operator overloading for classes.
A(:,n), A(m,:),
A(:), and A(j:k) are common indexing
expressions for a matrix A that contain a colon. When you use
a colon as a subscript in an indexing expression, such as
A(:,n), it acts as shorthand to include
all subscripts in a particular array dimension. It is
also common to create a vector with a colon for the purposes of indexing, such
as A(j:k). Some indexing expressions combine both uses of the
colon, as in A(:,j:k).
Common indexing expressions that contain a colon are:
A(:,n)is thenth column of matrixA.A(m,:)is themth row of matrixA.A(:,:,p)is thepth page of three-dimensional arrayA.A(:)reshapes all elements ofAinto a single column vector. This has no effect ifAis already a column vector.A(:,:)reshapes all elements ofAinto a two-dimensional matrix. This has no effect ifAis already a matrix or vector.A(j:k)uses the vectorj:kto index intoA. If A is a vector, thenA(j:k)has the same orientation asA. IfAis a matrix, thenA(j:k)is a row vector.A(:,j:k)includes all subscripts in the first dimension but uses the vectorj:kto index in the second dimension. This returns a matrix with columns[A(:,j), A(:,j+1), ..., A(:,k)].
Examples
Input Arguments
Output Arguments
Tips
The
forreference page has a description of how to use:in the context of loop statements.linspaceis similar to the colon operator:, but it gives direct control over the number of points and always includes the endpoints. The sibling functionlogspacegenerates logarithmically spaced values.When you create a vector to index into a cell array or structure array (such as
orcellName{:}), MATLAB returns multiple outputs in a comma-separated list. For more information, see How to Use Comma-Separated Lists.structName(:).fieldName