Matlab

How To Find Index of Element in Array in MATLAB

Locating the index of a particular element within an array is a frequently performed task in MATLAB. Whether you need to locate the position of a certain value or search for a particular element, MATLAB provides several methods to accomplish this task efficiently.

How to Find the Index of Element in an Array in MATLAB?

Arrays serve as potent tools for data storage and manipulation in MATLAB, enabling convenient indexing to access specific elements based on their assigned positions. By utilizing the index, a numerical representation denoting an element’s location within the array, one can effectively retrieve desired values; here are some ways for it:

Method 1: Using the find() Function

The find() function returns a vector of the indices of all the elements in an array that matches a specified condition. As an illustration, the subsequent code snippet demonstrates the process of determining the index of the initial occurrence of the value 10 within the array arr:

arr = [1, 2, 3, 10, 4, 5];

ind = find(arr == 10);

disp(ind);

The ind variable will now contain the value 3, which is the index of the first element in the array arr that is equal to 10:

Method 2: Using the ismember() Function

The ismember() function presents an additional technique to ascertain the index of an element within an array. This function checks whether each element of a given array is a member of a reference array and returns a logical array indicating the result.

arr = [1, 2, 3, 10, 4, 5];

ismember = ismember(arr, 10);

disp(ismember);

The ismember variable will now contain a vector of boolean values, where true indicates that the corresponding element in the array arr is equal to 10 and false indicates that it is not. The index of the first element in the array arr that is equal to 10 can be found by finding the first index where the ismember vector is equal to true.

Conclusion

Finding the index of an element in an array is a common task in MATLAB, and there are multiple ways to accomplish it. In this article, we explored three methods: using the find() function and the ismember() function.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.