MATLAB Answers

How to find vector elements indices for the first and last locations of a specific number?

23 views (last 30 days)
Tarek on 20 Apr 2021 at 13:15
Commented: Tarek on 20 Apr 2021 at 14:35
If I have a vector
I want to find the index of the first 20 and the index of the last 20.
Same for the index of the first 62 and last 62; first 112 and last 112, etc.
Is there a way to do this, without loops prefereably?

More Answers (1)

Image Analyst
Image Analyst on 20 Apr 2021 at 13:27
Edited: Image Analyst on 20 Apr 2021 at 13:55
If you have just those specific numbers, you can use find(). Otherwise you'd have to pass A into unique() and then use ismember(), like in David's answer. But to find just one number, you can use find():
first20 = find(A == 20, 1, 'first');
last20 = find(A == 20, 1, 'last');
first62 = find(A == 62, 1, 'first');
last62 = find(A == 62, 1, 'last');
FYI, don't worry about loops, they will be fast, especially for some array as microscopic as this. Here is how to find all of the first and last locations:
ua = unique(A)
numUniqueElements = length(ua)
firstLocations = zeros(numUniqueElements, 1);
lastLocations = zeros(numUniqueElements, 1);
for k = 1 : numUniqueElements
firstLocations(k) = find(A == ua(k), 1, 'first');
lastLocations(k) = find(A == ua(k), 1, 'last');
Elapsed time is 0.000501 seconds.
  1 Comment
Tarek on 20 Apr 2021 at 14:01
yeah exactly
i have 700,000 vectors like A and each different in length and elements from the other
the vector A was just a small example that covers alll the cases I might get.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by