查找非零元素的索引和值
k = find(X)
k = find(X,n)
k = find(X,n,direction)
[row,col] = find(___)
[row,col,v] = find(___)
返回一个向量, 其中包含数组 x 中每个非零元素的线性索引。k
= find(X
)
如果 X 是向量, 则 find 返回与 x 方向相同的向量。
如果 X 是多维数组, 则 find 返回结果的线性索引的列向量。
如果 X 不包含非零元素或为空, 则 find 返回空数组。
例子:
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
)
例子:
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 索引。k
= find(X
,n
,direction
)
例子:
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(___)
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(___)
非零元素的下标和值
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
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 函数在下标和线性索引之间转换时非常有用。