MATLAB Answers

How I can find index of element in array?

6,029 views (last 30 days)
I know, that number, for example, 5, is an element in array X, but I don't know it's index. In Python, I can use:
I realized this function, using for loop and if statement, but did Matlab doesn't have build-in similar function?

Accepted Answer

James Tursa
James Tursa on 8 Nov 2017
Edited: James Tursa on 8 Nov 2017
If you know the number exactly, then you can use:
result = find(X==5);
Scott MacKenzie
Scott MacKenzie on 18 Apr 2021
Bear in mind that if the number occurs more than once in the vector, the result returned is a vector containing the indices of all occurrences. If you want the index of just the first occurrence of the number, insert 1 as the second argument in find:
>> x = [3 4 5 6 4 8]
x =
3 4 5 6 4 8
>> result = find(x==4)
result =
2 5
>> result = find(x==4, 1)
result =

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!