How to group number sequences in a vector

2 visualizaciones (últimos 30 días)
Daniel Montano
Daniel Montano el 6 de Dic. de 2024
Comentada: Daniel Montano el 6 de Dic. de 2024
I have a vector containing 1s, 2s, and 3s. For example:
V1 = [1 1 1 2 2 3 3 3 1 1 3 3 3 2 2 2 1 1 1]
I need to get the start and ending points of all sequences of the form 3-2-1. For example, in the vector above, I would need to record index 11 and index 19. The vector is much larger than the one above, so multiple of the 3-2-1 sequences would be present and I would need to record all of those starting and ending points. My current best idea is to use some sort of counter that resets everytime a "3" is found and the diff with the previous number is positive (and the opposite for the ending "1") but the issue with this method is it would also record indexes of incomplete sequences such as 3-2 or 3-1. I am kind of stuck there, and I'm sure there's a step I am missing. Is there a better way to do this? Maybe a matlab functionality I'm not taking advantage of?

Respuesta aceptada

Stephen23
Stephen23 el 6 de Dic. de 2024
Editada: Stephen23 el 6 de Dic. de 2024
V1 = [1,1,1,2,2,3,3,3,1,1,3,3,3,2,2,2,1,1,1];
R1 = sprintf('\3+\2+\1+');
[Xs,Xe] = regexp(char(V1),R1)
Xs = 11
Xe = 19
Some values would require escaping in the regular expression.
  2 comentarios
John D'Errico
John D'Errico el 6 de Dic. de 2024
What I was thinking of doing. But in a much slicker way.
Daniel Montano
Daniel Montano el 6 de Dic. de 2024
This is amazing thank you

Iniciar sesión para comentar.

Más respuestas (1)

Fintan Healy
Fintan Healy el 6 de Dic. de 2024
Editada: Fintan Healy el 6 de Dic. de 2024
I would start by finding the:
  1. list of the starting numbers
  2. the index at the start and end of each contiguous section of numbers
then you can look for the pattern [3,2,1] in the starting numbers, and find the corresponding indicies in the other two vectors.
V1 = [1 1 1 2 2 3 3 3 1 1 3 3 3 2 2 2 1 1 1];
% find indicies where number changes (1 at start as the first element is valid)
dv = [1,V1(2:end)-V1(1:end-1)]~=0;
% get start value of each section
startValues = V1(dv);
% get start and end index of each section
startIdx = find(dv);
endIdx = find([dv(2:end),1]);
% find a pattern in the start indicies
ii = strfind(startValues,[3,2,1]);
for i = 1:length(ii)
% pattern found, print indicies
disp([startIdx(ii),endIdx(ii+2)])
end
11 19

Categorías

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

Etiquetas

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by