How to group number sequences in a vector

조회 수: 2 (최근 30일)
Daniel Montano
Daniel Montano 2024년 12월 6일
댓글: Daniel Montano 2024년 12월 6일
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?

채택된 답변

Stephen23
Stephen23 2024년 12월 6일
편집: Stephen23 2024년 12월 6일
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
John D'Errico
John D'Errico 2024년 12월 6일
What I was thinking of doing. But in a much slicker way.
Daniel Montano
Daniel Montano 2024년 12월 6일
This is amazing thank you

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Fintan Healy
Fintan Healy 2024년 12월 6일
편집: Fintan Healy 2024년 12월 6일
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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by