How to find vector elements indices for the first and last locations of a specific number?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
David Hill
2021-4-20
[~,idxfirst]=ismember(unique(A),A);
[~,idxlast]=ismember(unique(A),flip(A));
idxlast=length(A)+1-idxlast;
更多回答(1 个)
Image Analyst
2021-4-20
编辑:Image Analyst
2021-4-20
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!