Vector creation, array subscripting, andfor
-loop iteration
The colon is one of the most useful operators in MATLAB®. It can create vectors, subscript arrays, and specifyfor
iterations.
x = j k x = j:我:k (:, n) (m,:) A(:) A(j:k)
creates a regularly-spaced vectorx
=j
:i
:k
x
usingi
as the increment between elements. The vector elements are roughly equal to[j,j+i,j+2*i,...,j+m*i]
wherem = fix((k-j)/i)
. However, ifi
is not an integer, then floating point arithmetic plays a role in determining whethercolon
includes the endpointk
in the vector, sincek
might not beexactlyequal toj+m*i
. If you specify nonscalar arrays, then MATLAB interpretsj:i:k
asj(1):i(1):k(1)
.
x = colon(j,k)
andx = colon(j,i,k)
are alternate ways to execute the commandsj:k
andj:i:k
, but are rarely used. These syntaxes enable operator overloading for classes.
A(:,n)
,A(m,:)
,A(:)
, andA(j:k)
are common indexing expressions for a matrixA
that contain a colon. When you use a colon as a subscript in an indexing expression, such asA(:,n)
, it acts as shorthand to includeallsubscripts in a particular array dimension. It is also common to create a vector with a colon for the purposes of indexing, such asA(j:k)
. Some indexing expressions combine both uses of the colon, as inA(:,j:k)
.
Common indexing expressions that contain a colon are:
A(:,n)
is then
th column of matrixA
.
A(m,:)
is them
th row of matrixA
.
A(:,:,p)
is thep
th page of three-dimensional arrayA
.
A(:)
reshapes all elements ofA
into a single column vector. This has no effect ifA
is already a column vector.
A(:,:)
reshapes all elements ofA
into a two-dimensional matrix. This has no effect ifA
is already a matrix or vector.
A(j:k)
uses the vectorj:k
to index intoA
and is therefore equivalent to the vector[A(j), A(j+1), ..., A(k)]
.
A(:,j:k)
includes all subscripts in the first dimension but uses the vectorj:k
to index in the second dimension. This returns a matrix with columns[A(:,j), A(:,j+1), ..., A(:,k)]
.
Thefor
reference page has a description of how to use:
in the context of loop statements.
linspace
is similar to the colon operator:
, but it gives direct control over the number of points and always includes the endpoints. The sibling functionlogspace
generates 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, seeHow to Use the Comma-Separated Lists.structName
(:).fieldName