counting the number of times a number appears next to the same one in a row?

조회 수: 6 (최근 30일)
Yoanna Ivanova
Yoanna Ivanova 2019년 6월 22일
댓글: Bruno Luong 2019년 6월 22일
Hi everyone,
I am trying to generate a random sequence and for this I have a row vector, which contains the values 1 to 6 in a random order 4 times (so my vector has 24 elements). I need a way to find how many times the same number appears next to the same number - I have a hard time explaining what I mean but here is an example:
1 2 3 4 5 6 -- no same number appears next to the same number so answer should be 0
1 1 2 3 4 5 -- here 1 is repeated once, so answer should be 1
1 1 2 3 4 4 - here 1 and 4 are repeated and so the answer should be 2
  댓글 수: 3
madhan ravi
madhan ravi 2019년 6월 22일
vector = [1,1,1,5,6,2,2,3,1]
result = ???

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

답변 (4개)

madhan ravi
madhan ravi 2019년 6월 22일
Simpler:
nnz(~diff(vector))
Note: Taking into account that we only deal with integers.
  댓글 수: 5
Bruno Luong
Bruno Luong 2019년 6월 22일
Why you are saying "Taking into account that we only deal with integers."

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


KALYAN ACHARJYA
KALYAN ACHARJYA 2019년 6월 22일
편집: KALYAN ACHARJYA 2019년 6월 22일
num=[1 2 3 4 5 6]; % Change this one and test
uniq_num=unique(num);
digit_repeat=length(num)-length(uniq_num)
Its works right?

Bruno Luong
Bruno Luong 2019년 6월 22일
편집: Bruno Luong 2019년 6월 22일
>> A=[1 1 1 2 3 4 4 2]
A =
1 1 1 2 3 4 4 2
>> sum(diff(A)==0 & diff([NaN, A(1:end-1)])~=0)
ans =
2
>>

Kilian Liss
Kilian Liss 2019년 6월 22일
Probably not the most ellegant solution, but the following code seems to work:
x1 = [1 1 2 3 4 4];
count = 0;
for i = 1:length(x1) - 1
if(x1(i) == x1(i + 1))
count = count + 1;
end
end

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by