In MATLAB, the “:” operator can be used to create vectors, subscript arrays, and specify iterations, making it one of the most useful MATLAB operators.
The following example creates a row vector that includes numbers from 1 to 10:
1:10
When MATLAB executes this statement, it returns a row vector containing integers from 1 to 10:
ans = 1 2 3 4 5 6 7 8 9 10
If you want to specify a different increment value, for example:
100: -5: 50
When MATLAB executes this statement, it returns the following result:
ans = 100 95 90 85 80 75 70 65 60 55 50
Let’s look at another example:
0:pi/8:pi
When MATLAB executes this statement, it returns the following result:
ans = Columns 1 through 7 0 0.3927 0.7854 1.1781 1.5708 1.9635 2.3562 Columns 8 through 9 2.7489 3.1416
The colon “:” operator can be used to create vector indices to select elements from rows, columns, or arrays.
The table below describes its use for this purpose (let’s define a matrix A):
Format | Purpose |
---|---|
A(:,j) | is the j-th column of A |
A(i,:) | is the i-th row of A |
A(:,:) | is the equivalent two-dimensional array; for matrices, this is the same as A |
A(j:k) | is A(j), A(j + 1), …, A(k) |
A(:,j:k) | is A(:,j), A(:,j+1), …, A(:,k) |
A(:,:,k) | is the k-th page of the three-dimensional array A |
A(i,j,k,:) | is a vector in the four-dimensional array A; the vector includes A(i,j,k,1), A(i,j,k,2), A(i,j,k,3), etc. |
A(:) | is all elements of A, viewed as a single column; in an assignment statement on the left side, A(:) fills A while preserving its previous shape; in this case, the right side must contain the same number of elements as A. |
Detailed Example
Create a script file in MATLAB and enter the following code:
A = [1 2 3 4; 4 5 6 7; 7 8 9 10]A(:,2) % second column of AA(:,2:3) % second and third column of AA(2:3,2:3) % second and third rows and second and third columns
Run the file to display the following results:
A = 1 2 3 4 4 5 6 7 7 8 9 10
ans = 2 5 8
ans = 2 3 5 6 8 9
ans = 5 6 8 9