MATLAB 中的 Find()函数
MATLAB 中的find()函数用于查找非零元素或满足给定条件的元素的索引和值。关系表达式可以与 find 结合使用以查找满足给定条件的元素的索引。它返回一个包含线性索引的向量。
使用线性索引可以使用单个下标访问多维数组。 MATLAB 将数组视为单列向量,每一列都附加到前一列的底部。
例子:
For example consider the following 3×3 array A =
1 4 7
2 5 8
3 6 9
In this array all elements represents their linear index i.e. we can reference A(1,2) with A(4).
句法:
Below are various wasy to use the function:
- k = find(X): It returns the indices of all non zero elements.
- k = find(X, n): It returns the first n indices of non zero elements in X
- k = find(X, n, direction): direction can be ‘first’ or ‘last’. If direction is first, this function will return first n indices corresponding to non zero elements and if direction is last then this function will return last n indices corresponding to non zero elements
- [row, col] = find(): It is used to get row and column subscript for all non zero elements.
- [row, col, v] = find(): row and column will hold subscript for all non zero elements and v is a vector which will hold all the non zero elements.
Note: k will be of same orientation as X if X is a vector and if X is a multidimensional array then k will be a column vector which will hold linear indices.
示例 1:下面的代码将返回一维数组中非零元素的索引。
MATLAB
% Defining array
A = [1 2 3 0]
% Getting indices of non zero elements
find(A)
MATLAB
% Defining array
A = [1 2 0; 3 1 4; 5 6 7]
% Getting first 2 indices
find(A>3, 2)
MATLAB
% Defining array
A = [1 2 0; 3 1 4; 5 6 7]
% Getting row and column
[row, col] = find(A>3, 2, 'last')
MATLAB
% Defining array
A = [1 2 3 0]
% Getting indices of zero elements
find(~A)
输出:
示例 2:下面的代码将返回元素大于 3 的元素的前 2 个索引。
MATLAB
% Defining array
A = [1 2 0; 3 1 4; 5 6 7]
% Getting first 2 indices
find(A>3, 2)
输出:
示例 3:下面的代码将返回大于 3 的元素的最后 2 行和列索引。
MATLAB
% Defining array
A = [1 2 0; 3 1 4; 5 6 7]
% Getting row and column
[row, col] = find(A>3, 2, 'last')
输出:
所以,A(2, 3) 和 A(3, 3) 是最后一个大于 3 的元素。我们得到 (2, 3) 和 (3, 3) 作为输出,而不是 (3,2) 和 (3, 3) 因为 MATLAB 将数组视为单列向量,每一列都附加到前一列的底部。
示例 4:下面的代码将返回所有零元素的索引。此代码将否定运算符(~) 与 find函数结合使用。
MATLAB
% Defining array
A = [1 2 3 0]
% Getting indices of zero elements
find(~A)
输出: