English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
GNU Octave tutorialcolon(:)is one of the most useful operators in MATLAB. It is used to create vectors, index arrays, andSpecify the iteration
.1to10Please write to create a row vector containing-
1:10
MATLAB executes this statement and returns a row vector containing1to10a row vector of integers-
ans = 1 2 3 4 5 6 7 8 9 10
If you want to specify an increment value instead of a single value, for example-
100: -5: 50
MATLAB executes the statement and returns the following result-
ans = 100 95 90 85 80 75 70 65 60 55 50
Let's take another example-
0:pi/8:pi
MATLAB executes the statement and 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
You can use the colon operator to create index vectors to select rows, columns, or array elements.
The following table describes its use (let's have 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 equivalent to a 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(:,:). |
A(:,:,k) | is the k-thofpage of the three-dimensional array A |
A(i,j,k,:) | is a vector in the three-dimensional array A. A vector includes A(i,j,k,1), A(i,j,k,2), A(i,j,k,3). |
A(:) | All elements of A are considered as a single column. On the left side of the assignment statement, A(:) fills A and retains the previous shape. In this case, the right side must contain the same number of elements as A. |
Create a script file and enter the following code-
A = [1 2 3 4; 4 5 6 7; 7 8 9 10] A(:,2) % The second column of A A(:,2:3) % The second column and third column of A A(2:3,2:3) % Second row and third row, as well as second column and third column
When the file is executed, it displays the following result-
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