# 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
%
A=[0;0;0;0;20;20;20;20;0;0;0;0;62;62;62;0;0;0;112;112;112;112;0;0]
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?

David Hill on 20 Apr 2021 at 13:35
[~,idxfirst]=ismember(unique(A),A);
[~,idxlast]=ismember(unique(A),flip(A));
idxlast=length(A)+1-idxlast;
Tarek on 20 Apr 2021 at 14:35
very nice and simple. thank you!

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');
etc.
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:
A=[0;0;0;0;20;20;20;20;0;0;0;0;62;62;62;0;0;0;112;112;112;112;0;0]
ua = unique(A)
numUniqueElements = length(ua)
firstLocations = zeros(numUniqueElements, 1);
lastLocations = zeros(numUniqueElements, 1);
tic
for k = 1 : numUniqueElements
firstLocations(k) = find(A == ua(k), 1, 'first');
lastLocations(k) = find(A == ua(k), 1, 'last');
end
toc
Elapsed time is 0.000501 seconds.
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.