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

3 visualizaciones (últimos 30 días)
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?

Respuesta aceptada

David Hill
David Hill el 20 de Abr. de 2021
[~,idxfirst]=ismember(unique(A),A);
[~,idxlast]=ismember(unique(A),flip(A));
idxlast=length(A)+1-idxlast;

Más respuestas (1)

Image Analyst
Image Analyst el 20 de Abr. de 2021
Editada: Image Analyst el 20 de Abr. de 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.
  1 comentario
Tarek
Tarek el 20 de Abr. de 2021
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.

Iniciar sesión para comentar.

Categorías

Más información sobre Structures en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by