MATLAB Answers

How I can find index of element in array?

6,919 views (last 30 days)
Mykhailo Yaroshenko
Mykhailo Yaroshenko on 8 Nov 2017
Commented: Walter Roberson on 11 Sep 2021 at 19:26
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);
  5 Comments
Walter Roberson
Walter Roberson on 11 Sep 2021 at 19:26
What difficulty do you find with James' answer? He showed the find() function, which is the function defined to locate the places where a condition occurs.
If you need to have the exact question answered more clearly, "but did Matlab doesn't have build-in similar function?" then the answer to that is "NO, MATLAB does not have a built-in function in which you can provide only the array name and the value, and MATLAB will return all the indices of the value in the array."
Note: if you only need to know the first location, then you can also use
[~, result] = ismember(5, x)
result will be 0 if 5 is not present in x.

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!