What is the colon notation in MATLAB?
Overview
MATLAB is a high-performance multi-paradigm programming language and numerical computing environment developed by MathWorks. MATLAB lets you work with matrices, display functions and data, implement algorithms, create user interfaces, and interact with programs written in other languages.
The symbol colon (:) is used as an operator in MATLAB programming and is a commonly used operator. This operator is used to construct a vector that is defined by a simple expression, iterate over or subscribe to an array, or access a set of elements of an existing vector.
Application of the MATLAB colon notation
Below are examples of some applications of the MATLAB colon notation.
Example 1
We can use the colon operator to create a vector with evenly spaced numbers where the colon operator uses default increment/decrement values.
Code 1
X = 1:10
// X = 1 2 3 4 5 6 7 8 9 10
Code 2
X = 1:2:10
// X = 1 3 5 7 9 10
Code 3
X = 100:-15:25
// X = 100 85 70 55 40 25
Example 2
Let’s say we have this statement 0:pi/9:pi. MATLAB will execute the statement and return the following result:
Code 4
0:pi/9:pi
// ans =
// 0.00000 0.34907 0.69813 1.04720 1.39626 1.74533 2.0944 2.44346 2.79253 3.14159
Explanation
This command will sequentially print the values that lie in the range of 0 to pi(3.14159). Also note that after every iteration, the value will be incremented by pi/9 = 0.34907 factor.
Check the following table for syntaxes to do this in a matrix B.
Table
Syntax | Description |
| This is the ith row of B. |
| This is the jth column of B. |
| These are all elements of B that are considered a single column. On the left side of the assignment statement, B ( |
| This is B(j), B(j+1), B(j+2), B(j+3),...,B(k). |
| This is a vector of 4D array B. Vectors are B(i, j, k, 1), B(i, j, k, 2), B(i, j, k, 3), B( i, j, k, 4), etc. |
| This syntax can be used to transform the elements of matrix 'B' into a two-dimensional matrix. |
| This syntax can be used to store/retrieve data from 3D array B set in kth page. |
Code 5
Let’s create a script file and put the following code in it.
% The script file
B = [2 4 6 8; 10 12 14 16; 18 20 22 24]
B(:,1) % display 1st column of B
B(:,2) % display 2nd column of B
B(:,2:3) % display 2nd and 3rd column of B
B(2:3,2:3) % display 2nd and 3rd rows and 2nd and 3rd columns
// B = 2 4 6 8
// 10 12 14 16
// 18 20 22 24
// ans = 2
// 10
// 18
// ans = 4
// 12
// 20
// ans = 4 6
// 12 14
// 20 22
// ans = 12 14
// 20 22
Explanation
In the above code:
B=[2 4 6 8; 10 12 14 16; 18 20 22 24]: Creates a 3x4 size matrixB.B(:,1): Displays the 1st column of matrixB.B(:,2): Displays the 2nd column of matrixB.B(:,2:3): Displays the 2nd and 3rd columns of matrixB.B(2:3,2:3): Displays the rows (2nd and 3rd) and columns (2nd and 3rd) of matrixB.