Is there a way to count the number of sequential values in a vector?

2 views (last 30 days)
I have some data with a few sporadic values with several zeros in between. I want to know the number of times that there are two or more values occurring together.
For example if I have
(a) [1 1 0 1 1 0 1 1]
then there are 3 sets of strings
If I have
(b) [1 0 0 1 1 1 0 0]
then there is one string
I have a function that can out put the location of all the nonzero numbers to get
(a) [1 2 4 5 7 8]
or
(b) [1 4 5 6]
and then I have a function that finds the difference between locations so that if two numbers are next to each other, it will output a 1 and if they are not then the number will be higher. For example
(a) [1 2 1 2 1]
(b) [3 1 1]
But I don't know how to get at my overall question. Suggstions?

Answers (3)

Jos (10584)
Jos (10584) on 27 Sep 2013
Here is a two-step suggestion: 1. set all the single 1's to 0 2. find the indices
x = [1 0 1 1 1 0 0 1 0 1 1] % data
idx = find(strrep([0 x 0],[0 1 0],[0 0 0]))-1 % one-liner
You can ignore or turn off the warning ...

Image Analyst
Image Analyst on 27 Sep 2013
Edited: Image Analyst on 27 Sep 2013
For the first question about values of 0 and 1, you can use bwlabel() in the image Processing Toolbox to count the number of sets of 1's that are 2 long or longer.
[L, numberOfRegions] = bwlabel(bwareaopen(a));
Here's a full demo using both of your example arrays:
a = [1 0 1 1 0 1 1 0 1 1]; % Define sample data.
a2 = bwareaopen(a, 2); % Get rid of single 1's
[L, numberOfARegions] = bwlabel(a2); % do the count.
fprintf('The number of regions in "a" 2 long or longer = %d\n', ...
numberOfARegions); % Print to command window.
b = [1 0 0 1 1 1 0 0]; % Define sample data.
b2 = bwareaopen(b, 2); % Get rid of single 1's
[L, numberOfBRegions] = bwlabel(b2); % do the count.
fprintf('The number of regions in "b" 2 long or longer = %d\n', ...
numberOfBRegions); % Print to command window.
In the command window:
The number of regions in "a" 2 long or longer = 3
The number of regions in "b" 2 long or longer = 1
Two lines of code, or even 1, is by far the easiest way to do it since there are two built in functions that do exactly what you want . Do you have the Image Processing Toolbox? Type ver to find out.

Azzi Abdelmalek
Azzi Abdelmalek on 27 Sep 2013
a=[1 1 0 1 1 0 1 1];
b=[1 0 0 1 1 1 0 0];
ia=find(a) % Location of 1 in a
ib=find(b) % Location of 1 in b
ida=diff(ia);
ida(ida~=1)=2 % shows if values are near each other
idb=diff(ib);
idb(idb~=1)=3% shows if values are near each other

Community Treasure Hunt

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

Start Hunting!