J.Smith
J.Smith

Reputation: 335

Find indices of a number sequence

I have different matrixes looking something like this matrixExample = [NaN, NaN, 50, 50, 50, 70, 70, 40, 40, 90, 90, 20, 20, 20]

Is it possible to get the indices of a number sequence in that matrix? I know the matrix contains 70, 70, 40, 40, 90, 90 which is one sequence. Now I want to set it so if the matrix contain a sequence of 70, 40, 90 (something I set by myself) I want to get the indices where this sequence begin (70) and end (90). The numbers must come in that set order of numbers but the amount of numbers can differ, 70, 40, 40, 40, 40, 40, 90, 90, 90 would also count (and so on).

One last example: matrixExample = [NaN, NaN, 50, 70, 50, 80, 70, 60, 70, 70, 40, 40, 90, 90, 20, 20, 20]

find where the sequence 70, 40, 90 is and give start and end indices where 70 is the start and 90 is the end.

Help is hugely appreciated!!

Upvotes: 2

Views: 85

Answers (1)

Divakar
Divakar

Reputation: 221554

Here's a vectorized approach -

search_seq = [70,40,90];
idx = [1 find(diff(matrixExample)~=0)+1 numel(matrixExample)+1];
idx0 = strfind(matrixExample(idx(1:end-1)),search_seq)
start_idx = idx(idx0)
idx1 = idx0+numel(search_seq);
stop_idx = idx(idx1)-1

Sample runs

Case #1 :

>> matrixExample = [NaN, NaN, 50, 50, 50, 70, 70, 40, 40, 90, 90, 20, 20, 20];
start_idx =
     6
stop_idx =
    11

Case #2 :

>> matrixExample = [NaN, NaN, 50, 70, 50, 80, 70, 60, ...
    70, 70, 40, 40, 90, 90, 20, 20, 20];
start_idx =
     9
stop_idx =
    14

Upvotes: 4

Related Questions