MATLAB冒號符號
冒號(:)是最有用的運算符在MATLAB之一。它是用來創建矢量,下標數組和指定的迭代。
如果想創建一個行向量,包含從1到10的整數,如下:
1:10
MATLAB執行該語句,並返回一個行向量,包含從1到10的整數:
ans = 1 2 3 4 5 6 7 8 9 10
如果想指定以外的一個增量值,例如:
100: -5: 50
MATLAB執行該語句,並返回以下結果:
ans = 100 95 90 85 80 75 70 65 60 55 50
讓我們再舉一個例子:
0:pi/8:pi
MATLAB執行該語句,並返回以下結果:
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
可以使用冒號運算符來創建矢量指數選擇行,列或數組中的元素。
下表描述了其用於此目的(讓我們有一個矩陣A):
格式 | 目的 |
---|---|
A(:,j) | is the jth column of A. |
A(i,:) | is the ith 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 kth page of three-dimensional array A. |
A(i,j,k,:) | is a vector in four-dimensional array A. The vector includes A(i,j,k,1), A(i,j,k,2), A(i,j,k,3), and so on. |
A(:) | is all the elements of A, regarded as a single column. On the left side of an assignment statement, A(:) fills A, preserving its shape from before. In this case, the right side must contain the same number of elements as A. |
例子
創建一個腳本文件,並鍵入下麵的代碼:
A = [1 2 3 4; 4 5 6 7; 7 8 9 10] A(:,2) % second column of A A(:,2:3) % second and third column of A A(2:3,2:3) % second and third rows and second and third columns
當您運行該文件,它會顯示以下結果:
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