colon - Vector creation, array subscripting, and for-loop
iteration - MATLAB ([original](https://in.mathworks.com/help/matlab/ref/double.colon.html)) ([raw](?raw))
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 specifyfor
iterations.
[x](#bvg1wnp-x) = [j](#bvg1wnp-j):[k](#bvg1wnp-k)
creates a unit-spaced vector x
with elements[j,j+1,j+2,...,j+m]
where m = fix(k-j)
. If j
and k
are both integers, then this is simply [j,j+1,...,k]
.
[x](#bvg1wnp-x) = [j](#bvg1wnp-j):[i](#bvg1wnp-i):[k](#bvg1wnp-k)
creates a regularly-spaced vector x
usingi
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 whethercolon
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
andj: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 asA(:,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 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
. If A is a vector, thenA(j:k)
has the same orientation asA
. IfA
is a matrix, thenA(j:k)
is a row vector.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)]
.
Examples
Create a unit-spaced vector of numbers between 1 and 10. The colon operator uses a default increment of +1.
x = 1×10
1 2 3 4 5 6 7 8 9 10
Create vectors that increment or decrement by a specified value.
Create a vector whose elements increment by 0.1.
x = 1×11
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000
Create a vector whose elements decrement by -2.
Examine several ways to index a matrix using a colon :
.
Create a 3-by-3 matrix. Index the first row.
A = 3×3
8 1 6
3 5 7
4 9 2
Index the second and third column.
Reshape the matrix into a column vector.
ans = 9×1
8
3
4
1
5
9
6
7
2
In the context of a for
-loop, the colon specifies the loop iterations.
Write a for
-loop that squares a number for values of n
between 1 and 4.
Input Arguments
Starting vector value, specified as a real numeric scalar. If j < k
so that the output vector is not empty, thenj
is the first element in the vector.
Example: x = 0:5
Example: x = 0:0.5:5
Data Types: single
| double
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
| char
| datetime
| duration
Ending vector value, specified as a real numeric scalar.k
is the last value in the vector only when the increment lines up to exactly land on k
. For example, the vector 0:5
includes 5 as the last value, but0:0.3:1
does not include the value 1 as the last value since the increment does not line up with the endpoint.
Example: x = 0:5
Example: x = 0:0.5:5
Data Types: single
| double
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
| char
| datetime
| duration
Increment between vector elements, specified as a real numeric scalar.
Example: x = 0:0.5:5
Data Types: single
| double
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
| char
| datetime
| duration
Output Arguments
Regularly-spaced vector, returned as a row vector. If j > k
, then x = j:k
is an empty matrix. More generally, the syntax x = j:i:k
returns an empty matrix when:
i
,j
, ork
is an empty inputi == 0
i > 0
andj > k
i < 0
andj < k
Tips
- The for 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 function logspace generates logarithmically spaced values. - 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 Comma-Separated Lists.
Extended Capabilities
Usage notes and limitations:
- Complex inputs are not supported.
- The input
i
cannot have a logical value. - Vector inputs are not supported.
- Inputs must be constants.
- Uses single-precision arithmetic to produce single-precision results.
The colon
function supports GPU array input with these usage notes and limitations:
- To run this function on a GPU and obtain a
gpuArray
output, use any of the following syntaxes:
x = gpuArray.colon(j,k)
x = gpuArray.colon(j,i,k)
Alternatively, you can also passgpuArray
objects directly to the colon operator:
x = gpuArray(j):gpuArray(k)
x = gpuArray(j):gpuArray(i):gpuArray(k) - 64-bit integers are not supported.
For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).
Version History
Introduced before R2006a
colon
now returns an error when creating vectors if one or more operands are not scalar. For example, expressions like [1 2 3]:2:10
now error. Previously, colon
used the first element of any nonscalar operands to evaluate the expression.
To preserve the behavior of previous releases, update your code to specify the first element of any nonscalar operands in place of those nonscalar operands. For example, this code now returns an error because size(A)
is nonscalar.
A = randn(3,4); v = 1:size(A)
In previous releases, this code was equivalent tov = 1:3
because size(A)
returned the vector [3 4]
, and colon
used only the size of the first dimension of A
to evaluate the expression. To achieve the same result, explicitly specify the size of the first dimension ofA
as the operand.
As another example, this code also returns an error because id
is nonscalar.
id = find([1 2 3 1 2 3] == 3); v = 1:id
In previous releases, this code was equivalent tov = 1:3
because find
returned the vector[3 6]
and colon
used only the first element of this returned vector to evaluate the expression. To achieve the same result, explicitly specify the first element of the vector as the operand.
Alternatively, you can directly specify that find
return only the first index.
id = find([1 2 3 1 2 3] == 3,1,"first"); v = 1:id
If you have a vector of sorted values, you can also use the min
function to access the first element of the vector. For example, this code now returns an error because strfind
returns a vector.
path = 'matlab/users/username/examples'; topDirname = path(1:strfind(path,'/')-1)
To achieve the same result as in previous releases, use the min
function on the sorted vector returned bystrfind
.
topDirname = path(1:min(strfind(path,'/'))-1)
colon
now issues a warning when creating vectors if one or more operands are not scalar. For example, expressions like [1 2 3]:2:10
now warn. This warning will become an error in a future release, removing support for nonscalar operands. Previously,colon
used the first element of any nonscalar operands to evaluate the expression.