campare a row value with the next row

Hi
I have the following column:
1
1
0
0
0
1
0
1
0
1
I want to campare rows value one by one with the next row ( first with second, second with third ... and ninth with tenth) and check if it changes for 1 to 0, 0 to 0, 0 to 1 and 1 to 1. For each of these conditions, I want to count them. I tried using loop and diff or sign and equations but I could not work out because the results will be similar for two conditions.

 Accepted Answer

You were close when using diff. You need to think what characterizes all four combinations. The code below should be what you need.
v=[1;1;0;0;0;1;0;1;0;1];
d=diff(v);
u=v(1:(end-1));%shrink by 1 to make it the same size as d
clc
%if [0;0]
%then diff==0, v==0
L= d==0 & u==0;
fprintf('[0 0]: %d\n',sum(L))
%if [0;1]
%then diff==-1
L= d==-1;
fprintf('[0 1]: %d\n',sum(L))
%if [1;0]
%then diff==1
L= d==1;
fprintf('[1 0]: %d\n',sum(L))
%if [1;1]
%then diff==0, v==1
L= d==0 & u==1;
fprintf('[1 1]: %d\n',sum(L))

More Answers (1)

Alex Mcaulley
Alex Mcaulley on 20 Feb 2020
Edited: Alex Mcaulley on 20 Feb 2020
Another option:
a = [1;1;0;0;0;1;0;1;0;1];
b = diff(a);
b(~b) = 2*a(~b);
sol = splitapply(@numel,b,b+2) %Ordered as [1,0],[0,0],[0,1],[1,1]
sol =
3 2 3 1

4 Comments

Dear Alex
I have two problem when I want to use this code in a loop. diff gives 0 result for both changes from 1 to 1 and 0 to 0. When I use it without loop I got 2 (for 1 to 1) and 0 for 0 to 0 (like the code above). The other thing is when the count for one condition is 0 and I do not see 0 in results and I see only three result which is confusing. The code below is what I tried.
my data: 2*20 >>> I want to calulate the second column.
0 0
0 1
1 0
0 0
1 0
0 1
1 0
1 1
0 0
1 1
1 1
0 0
0 1
1 0
0 1
0 1
0 1
1 1
1 0
1 1
converted = table2array(imported);
n=2;
C=permute(reshape(converted,10,n,2), [1 3 2]);
for ind = 1:n
D = C(:,2,ind);
b = diff(D);
b(~b) = 2*D(~b);
sol= splitapply(@numel,b,b+2);
soll{ind}=sol
end
Error using splitapply (line 111)
For N groups, every integer between 1 and N must occur at least once in the vector of group numbers.
With your second column it should work fine, because you have all the possible combinations.
I think this is the reason:
I think if one condition result is 0 then I will get the error.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 20 Feb 2020

Commented:

on 21 Feb 2020

Community Treasure Hunt

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

Start Hunting!