detecting 6 ones in a vector

i need a code to detect 6 consecutive ones in a vector and their places in the vector

3 Comments

What if there are 10 ones in a row? You could fit 6 in there in a bunch of places. Would you want the only starting index of the run of 10 elements? Would you want all elements that are part of the 10? Or do you just want the 5 starting indices of where a segment of 6 could fit? You need to clarify because these would be three different algorithms.
@jgg (Findsubmat) geives me an error message(undefined function for variable double ) @Imag Analyst i have a very big vector consists of zeros and ones...i need to find every 6 consecutive ones and add 0 after them...every 6 consecutive ones put 0...that what i want

Sign in to comment.

 Accepted Answer

John D'Errico
John D'Errico on 23 Dec 2015
Edited: John D'Errico on 23 Dec 2015
Trivially, in one line, just us strfind, a tool that works on numeric vectors as well as strings.
% A test case:
V = rand(1,1000) > 0.5;
ind = strfind(V,ones(1,6))
ind =
323 371 411 412 413 533 576 577 578 600 650 651 652 865 894 955 956 957 958
The vector ind contains the location of the start point of any string of 6 consecutive ones. For example, it found 411, 412, 413, so there was actually a string of 8 consecutive ones, and at the end, a strong of 9 consecutive ones.
If your goal is to find EXACTLY a string of only 6 ones, then use the pattern [0 1 1 1 1 1 1 0]. You would also need to test the first 6 and the last 6 elements then.
Or, you could append a zero to the start and end of the string of elements. Then no special test at the ends would be needed.
So this test will identify strings of EXACTLY 6 ones:
ind = strfind([0,V,0],[0 1 1 1 1 1 1 0])
ind =
323 371 533 600 865 894

3 Comments

isn't there any other finction that returns the last indices of the occurrences ?
Why do you need another tool?
If the string of interest is known to be 6 elements long, just add 5 to the start point to get the index of the end point.
ok that works with me .. thank u alot :)) i have another question how can i insert an element in a row verctor between 2 elements without replacing any of the matrix elements

Sign in to comment.

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 23 Dec 2015
Edited: Andrei Bobrov on 23 Dec 2015
b = A == 1; % A - your array
t = [true;diff(b)~=0];
n = find(t);
p = [n,diff([n;numel(A)+1])];
out1 = p(A(n)==1,:);
out = out1(out1(:,2)==6,:);
or with Image Processing Toolbox
c = regionprops(A(:) == 1,'BoundingBox');
k = cat(1,c.BoundingBox);
out = ceil(k(k(:,4)==6,[2,4]));

Categories

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!