How to Find Indices and Values of Nonzero Elements in MATLAB?
Last Updated :
02 Nov, 2022
MATLAB provides functionality that finds the indices and values of all non-zero elements in a vector or multidimensional array; the find() function. The find function with required parameters gives back a vector containing indices of non-zero elements in the passed array/vector.
Syntax:
vec = [] %some vector or array
indices = find(vec,…);
Here, the vec could be a vector or array. The indices vector stores the indices of non-zero elements in vec. Now, let us see different forms of find with the help of examples.
Finding non-zero elements’ indices in a vector.
Example 1:
Matlab
vec = [1 0 2 2 4 3 5 0 76 23 0.1 -1 0];
indices = find(vec);
disp(indices)
|
Output:
When an array is passed to the find() function, it returns a column vector that stores the linear indices of non-zero elements i.e., indexing when counting each element column-wise.
Example 2:
Matlab
vec = [1 0 2 2 4;
3 5 0 76 23;
0.1 -1 0 23 0];
indices = find(vec);
disp(indices)
|
Output:
We can find the indices of n non-zero elements from starting from the beginning or end as well.
Example 3:
Matlab
vec = [1 0 2 2 4;
3 5 0 76 23;
0.1 -1 0 23 0];
indices_first = find(vec,7, "first" );
indices_last = find(vec,7, "last" );
|
Output:
Note: In case “first” or “last” is not specified, MATLAB takes “first” as a default setting.
Getting Values of Non-Zero Elements With Indices:
We can also get the values of non-zero elements along with their indices.
Example 4:
Matlab
vec = [1 0 2 2 4;
3 5 0 76 23;
0.1 -1 0 23 0];
[row_ind, col_ind, values] = find(vec,7, "first" );
|
Output:
This will create three vectors:
- row_ind will store the row number of non-zero elements.
- col_ind will store the column number of non-zero elements.
- values store the values of non-zero elements.
The same can be done with vectors. In that case, one row_ind or col_ind will remain a constant vector.
Example 5:
Matlab
vec = [1 0 2 2 4 3 5 0 76 23 0.1 -1 0 23 0];
[row_ind, col_ind, values] = find(vec,7, "first" );
|
Output:
Share your thoughts in the comments
Please Login to comment...