Reputation: 79
I want to write a short Matlab function for finding the sequence values in a time series like this:
Ex: a = [0 0 0 1 0 0 1 1 0 1 1 1 1 0 0];
My_expected_result = 3 ;(as number 1 happens 3 time of sequences)
Thank you.
Upvotes: 0
Views: 46
Reputation: 112659
Here's a simple regexp
-based solution to find the number of runs of ones:
result = numel(regexp(char(a+'0'), '1+'));
You can also use strfind
, which works for numerical arrays (although that's not documented):
result = numel(strfind([0 a], [1 0]));
Or just diff
:
result = sum(diff([a 0])<0);
If you have the Image Processing Toolbox, bwlabel
can be used for the job too:
result = max(bwlabel(a));
or (thanks to @rahnema1 for this one):
[~, result] = bwlabel(a);
Upvotes: 3