How to find vector elements indices for the first and last locations of a specific number?
2 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
David Hill
on 20 Apr 2021
[~,idxfirst]=ismember(unique(A),A);
[~,idxlast]=ismember(unique(A),flip(A));
idxlast=length(A)+1-idxlast;
More Answers (1)
Image Analyst
on 20 Apr 2021
Edited: Image Analyst
on 20 Apr 2021
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.
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!