How to count alternating ones and zeros in a matrix
Show older comments
Lets just say that I have a matrix v as following:
v =
0 0 0 0 0 0
1 1 0 1 1 0
1 0 1 0 1 0
0 0 1 0 1 0
0 0 0 1 1 1
I want to get rows where alternating ones and zeros are occuring which are 3rd and 4th rows. By alternating ones and zeros, I mean a sequence of [1 0 1 0] at least.
2 Comments
Walter Roberson
on 14 Jul 2021
How about if a row ends with 0 1 0 1, is that also alternating 0 and 1, or does the sequence have to start with a 1?
Awais Saeed
on 14 Jul 2021
Accepted Answer
More Answers (2)
v =[
0 0 0 0 0 0
1 1 0 1 1 0
1 0 1 0 1 0
0 0 1 0 1 0
0 0 0 1 1 1];
A=v(:,1:end-3); B=v(:,2:end-2); C=v(:,3:end-1); D=v(:,4:end);
pattern1=A==0 & B==1 & C==0 & D==1;
pattern2=A==1 & B==0 & C==1 & D==0;
rows=find( any(pattern1|pattern2,2) )
1 Comment
Stephen23
on 15 Jul 2021
+1 nice use of MATLAB.
v =[ 0 0 0 0 0 0; ...
1 1 0 1 1 0; ...
1 0 1 0 1 0; ...
0 0 1 0 1 0; ...
0 0 0 1 0 1; ... Walter Roberson's suggestion,
1 0 1 0 0 0; ... and reversed also.
0 1 0 1 0 1; ... Entire row alternating.
0 0 0 1 1 1];
X = any(diff(v,3,2)>3 | diff(~v,3,2)>3, 2)
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!