Open In App

How to Find Indices and Values of Nonzero Elements in MATLAB?

Improve
Improve
Like Article
Like
Save
Share
Report

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




% MATLAB code for indices
% Vector 
vec = [1 0 2 2 4 3 5 0 76 23 0.1 -1 0];    
  
% Getting indices
indices = find(vec);
  
% Displaying the indices
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




% MATLAB code for vector
% 2D array
vec = [1 0 2 2 4;
       3 5 0 76 23;
       0.1 -1 0 23 0];    
  
% Getting indices
indices = find(vec);    
  
% Displaying indices
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




% MATLAB code for indices with non-zero elements
vec = [1 0 2 2 4;
       3 5 0 76 23;
       0.1 -1 0 23 0];
         
% Getting first 7 non-zero elements' indices
indices_first = find(vec,7,"first");    
  
% Getting last 7 non-zero elements' indices
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




% MATLAB code 
% Array
vec = [1 0 2 2 4;
       3 5 0 76 23;
       0.1 -1 0 23 0];    
  
% Getting row, column value of non
% zero element with their values
[row_ind, col_ind, values] = find(vec,7,"first");


Output:

This will create three vectors:

  1. row_ind will store the row number of non-zero elements.
  2. col_ind will store the column number of non-zero elements.
  3. 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




% MATLAB code for vector
vec = [1 0 2 2 4 3 5 0 76 23 0.1 -1 0 23 0];    
  
% Getting the values of row, col, 
% and values of non-zero element
[row_ind, col_ind, values] = find(vec,7,"first");


Output:

 



Last Updated : 02 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads