How to group number sequences in a vector
조회 수: 2 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
추가 답변 (1개)
Fintan Healy
2024년 12월 6일
편집: Fintan Healy
2024년 12월 6일
I would start by finding the:
- list of the starting numbers
- 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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!