【 MATLAB 】find 函式的使用(線性索引)
find
查詢非零元素的索引和值
Syntax
k = find(X)
k = find(X,n)
k = find(X,n,direction)
[row,col] = find(___)
[row,col,v] = find(___)
Description
返回一個向量, 其中包含陣列 x 中每個非零元素的線性索引。k
= find(X
)
-
如果 X 是向量, 則 find 返回與 x 方向相同的向量。
-
如果 X 是多維陣列, 則 find 返回結果的線性索引的列向量。
-
如果 X 不包含非零元素或為空, 則 find 返回空陣列。
例子:
Zero and Nonzero Elements in Matrix
Find the nonzero elements in a 3-by-3 matrix.
X = [1 0 2; 0 1 1; 0 0 4]
X = 3×3 1 0 2 0 1 1 0 0 4
k = find(X)
k = 5×1 1 5 7 8 9
Use the logical not
operator on X
to locate the zeros.
k2 = find(~X)
k2 = 4×1 2 3 4 6
返回與 x 中的非零元素對應的前 n 個索引。k
= find(X
,n
)
例子:
Elements Satisfying a Condition
Find the first five elements that are less than 10 in a 4-by-4 magic square matrix.
X = magic(4)
X = 4×4 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1
k = find(X<10,5)
k = 5×1 2 3 4 5 7
View the corresponding elements of X
.
X(k)
ans = 5×1 5 9 4 2 7
, 如果方向為 "last", 則查詢與 x 中的非零元素對應的最後 n 個索引。directionis "first" 的預設值, 它查詢與非零元素對應的第一個 n 索引。
例子:
Last Several Nonzero Elements
Create a 6-by-6 magic square matrix with all of the odd-indexed elements equal to zero.
X = magic(6); X(1:2:end) = 0
X = 6×6 0 0 0 0 0 0 3 32 7 21 23 25 0 0 0 0 0 0 8 28 33 17 10 15 0 0 0 0 0 0 4 36 29 13 18 11
Locate the last four nonzeros.
k = find(X,4,'last')
k = 4×1 30 32 34 36
x(k)
ans =
18 25 15 11
[
使用以前的語法中的任何輸入引數返回陣列 X 中每個非零元素的行和列下標。row
,col
] = find(___)
Elements Satisfying Multiple Conditions
Find the first three elements in a 4-by-4 matrix that are greater than 0
and less than 10
. Specify two outputs to return the row and column subscripts to the elements.
X = [18 3 1 11; 8 10 11 3; 9 14 6 1; 4 3 15 21]
X = 4×4 18 3 1 11 8 10 11 3 9 14 6 1 4 3 15 21
[row,col] = find(X>0 & X<10,3)
row = 3×1 2 3 4
col = 3×1 1 1 1
The first instance is X(2,1)
, which is 8
.
[
還返回向量 v, 其中包含 x 的非零元素。row
,col
,v
] = find(___)
Subscripts and Values for Nonzero Elements
非零元素的下標和值
Find the nonzero elements in a 3-by-3 matrix. Specify three outputs to return the row subscripts, column subscripts, and element values.
X = [3 2 0; -5 0 7; 0 0 1]
X = 3×3 3 2 0 -5 0 7 0 0 1
[row,col,v] = find(X)
row = 5×1 1 2 1 2 3
col = 5×1 1 1 2 3 3
v = 5×1 3 -5 2 7 1
Subscripts of Multidimensional Array
Find the nonzero elements in a 4-by-2-by-3 array. Specify two outputs, row
and col
, to return the row and column subscripts of the nonzero elements. When the input is a multidimensional array (N > 2
), find
returns col
as a linear index over the N-1
trailing dimensions of X
.
X = zeros(4,2,3); X([1 12 19 21]) = 1
X = X(:,:,1) = 1 0 0 0 0 0 0 0 X(:,:,2) = 0 0 0 0 0 0 1 0 X(:,:,3) = 0 1 0 0 1 0 0 0
[row,col] = find(X)
row = 4×1 1 4 3 1
col = 4×1 1 3 5 6
最後介紹下線性索引:
線性索引允許使用單個下標索引到陣列中, 如 a (k)。MATLAB®將陣列視為單個列向量, 並將每個列附加到上一列的底部。因此, 線性索引將列中的元素從上到下、從左到右編號。
例如, 考慮一個3乘3矩陣。您可以引用 a (22) 元素與 a (5) 和 a (23) 元素具有 a (8)。線性索引根據陣列的大小而變化;a (5) 返回一個3乘3矩陣的不同位置的元素, 而不是4到4矩陣。
sub2ind 和 ind2sub 函式在下標和線性索引之間轉換時非常有用。