How to Use Colon Operator in MATLAB: Syntax and Examples
In MATLAB, the
colon operator (:) creates regularly spaced vectors and selects parts of arrays. Use start:step:end to generate sequences or A(:,2) to select all rows of the second column in matrix A.Syntax
The colon operator has two main forms:
start:end: creates a vector fromstarttoendwith step size 1.start:step:end: creates a vector fromstarttoendwith increments ofstep.
It is also used for indexing arrays, where : means all elements in that dimension.
matlab
v1 = 1:5; v2 = 0:2:10; A = [1 2 3; 4 5 6; 7 8 9]; col2 = A(:,2);
Output
v1 =
1 2 3 4 5
v2 =
0 2 4 6 8 10
col2 =
2
5
8
Example
This example shows how to create a vector with the colon operator and how to extract a submatrix from a matrix.
matlab
vec = 3:3:15; M = [10 20 30 40; 50 60 70 80; 90 100 110 120]; subM = M(1:2, 2:3);
Output
vec =
3 6 9 12 15
subM =
20 30
60 70
Common Pitfalls
Common mistakes include:
- Using a step size of zero, which causes an error.
- Forgetting that the
endvalue is included only if the sequence fits exactly. - Using the colon operator incorrectly for indexing, such as mixing row and column indices.
Example of wrong and right usage:
matlab
% Wrong: step size zero % v = 1:0:5; % This causes an error % Right: v = 1:1:5;
Output
v =
1 2 3 4 5
Quick Reference
| Usage | Description | Example |
|---|---|---|
| start:end | Vector from start to end with step 1 | 1:5 โ [1 2 3 4 5] |
| start:step:end | Vector from start to end with step size | 0:2:6 โ [0 2 4 6] |
| : | All elements in a dimension (indexing) | A(:,3) โ all rows, 3rd column |
| end | Last index of dimension | A(2:end, :) โ rows 2 to last, all columns |
Key Takeaways
The colon operator creates vectors with regular steps using start:step:end syntax.
Use colon operator for selecting all elements in a matrix dimension with : in indexing.
Step size cannot be zero; it must be a positive or negative number.
The end keyword represents the last index in an array dimension.
Colon operator is essential for slicing and generating sequences efficiently in MATLAB.