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!