How to detect a sequence in an array [extended]

Hello everybody,
let's say, I have this sequence: 1 - 770 - ... (unknow amount of uninteresting numbers shortened with uaun) ... - 897 - uaun - 769 - uaun - 897 - uaun - (continues in any way)
I would like to be able to detect how many times 770 is followed by 897 followed by 769. Additionally, I would like to calculate how many times 769 is followed by 897. 770-uaun-897-uaun-769-uaun-897 counts for both events.
Can someone think of an elegant way to program this? I can only think of an unbelievable complicated program with a lot of while-loops and break-commands.
Thank you in advance!
Marcus

4 Comments

As a first step, to reduce the overall computational burden, you can do
x = intersect(x,[770 897 769]);
to remove the irrelevant elements.
What should the two counts be for this vector?
x = [770 897 769 770 897 769 897]
? I'm specifically wondering if the 897-769 after the second 770 also count toward the first 770, which they also follow.
Hi the cyclist,
event(770-897-769) happens in x twice: x(1)-x(2)-x(3) and x(4)-x(5)-x(6).
event(769-897) happens in x once. x(6)-x(7)
769 and 770 are "breaking" the sequence.
intersect won't work since it removes all duplicates. Filtering with ismember would.
Crap. That's the first way I posted it -- then thought I had found some more elegant. Fail.
x = x(ismember(x,[770 897 769]));

Sign in to comment.

 Accepted Answer

v = [1 770 2 3 4 5 6 897 7 8 769 9 10 11 897 12 13 14 770 15 770 897 769] %demo data
filteredv = v(ismember(v, [770 769 897])); %get rid of uaun
seq1count = numel(strfind(filteredv, [770 897 769])) %despite its name strfind works with sequence of numbers
seq2count = numel(strfind(filteredv, [769 897]))

5 Comments

well done!!! Thank you!!!
One more thing: I would like to know the position in the sequence of the last value which completes the event(770-897- 769) or event(769- 897)
seq1pos = strfind(filteredv, [770 897 769]) + 2;
seq2pos = strfind(filteredv, [769 897]) + 1;
seq1count = numel(seq1pos);
seq2count = numel(seq2pos);
I forgot to say that the fact that strfind works with sequences of numbers is not documented. So possibly, in a future version of matlab, it may stop doing so.
Your code
seq1pos = strfind(filteredv, [770 897 769]) + 2
finds the event(770-897-769) in filteredv.
I would like to find the position of the event in v aka demo data.
Oh yes, of course!
v = [1 770 2 3 4 5 6 897 7 8 769 9 10 11 897 12 13 14 770 15 770 897 769] %demo data
filter = ismember(v, [770 769 897]);
filteredv = v(filter);
origlocs = find(filter);
locendfiltered = strfind(filteredv, [770 897 769]) + 2;
locendv = origlocs(locendfiltered)
seqcount = numel(locendv)
Perfect!!! Thank you!!! Fun fact: your solution is around 50 lines shorter than mine... ;-D

Sign in to comment.

More Answers (0)

Products

Tags

Community Treasure Hunt

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

Start Hunting!