MATLAB Answers

How I can find index of element in array?

10,753 views (last 30 days)
Mykhailo Yaroshenko
Mykhailo Yaroshenko on 8 Nov 2017
Edited: Scott MacKenzie on 18 Apr 2021 at 12:06
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:
X.index(5)
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);
  2 Comments
Scott MacKenzie
Scott MacKenzie on 18 Apr 2021 at 11:47
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 =
2

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!