campare a row value with the next row

조회 수: 8 (최근 30일)
Boby S
Boby S 2020년 2월 20일
댓글: Boby S 2020년 2월 21일
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.

채택된 답변

Rik
Rik 2020년 2월 20일
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))

추가 답변 (1개)

Alex Mcaulley
Alex Mcaulley 2020년 2월 20일
편집: Alex Mcaulley 2020년 2월 20일
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
Alex Mcaulley
Alex Mcaulley 2020년 2월 21일
With your second column it should work fine, because you have all the possible combinations.
Boby S
Boby S 2020년 2월 21일
I think this is the reason:
I think if one condition result is 0 then I will get the error.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by