VOOZH about

URL: https://www.geeksforgeeks.org/matlab/how-to-find-indices-and-values-of-nonzero-elements-in-matlab/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 28 Apr, 2025

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:

Output:

👁 Image
 

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:

Output:

👁 Image
 

We can find the indices of n non-zero elements from starting from the beginning or end as well.

Example 3:

Output:

👁 Image
 

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:

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.
👁 Image
 

The same can be done with vectors. In that case, one row_ind or col_ind will remain a constant vector. 

Example 5:

Output:

👁 Image
 
Comment