Asked by Yoanna Ivanova
on 22 Jun 2019 at 9:40

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

Answer by madhan ravi
on 22 Jun 2019 at 11:22

Simpler:

nnz(~diff(vector))

Note: Taking into account that we only deal with integers.

Bruno Luong
on 22 Jun 2019 at 11:53

"Note: Taking into account that we only deal with integers."

Why ?

madhan ravi
on 22 Jun 2019 at 12:00

Huh? What kind of question is that?

Bruno Luong
on 22 Jun 2019 at 12:02

Why you are saying "Taking into account that we only deal with integers."

Sign in to comment.

Answer by KALYAN ACHARJYA
on 22 Jun 2019 at 10:01

Edited by KALYAN ACHARJYA
on 22 Jun 2019 at 10:15

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?

Sign in to comment.

Answer by Bruno Luong
on 22 Jun 2019 at 10:27

Edited by Bruno Luong
on 22 Jun 2019 at 10:29

>> 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

>>

Sign in to comment.

Answer by Kilian Liss
on 22 Jun 2019 at 10:32

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

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 3 Comments

## Kilian Liss (view profile)

Direct link to this comment:https://in.mathworks.com/matlabcentral/answers/468372-counting-the-number-of-times-a-number-appears-next-to-the-same-one-in-a-row#comment_717199

## madhan ravi (view profile)

Direct link to this comment:https://in.mathworks.com/matlabcentral/answers/468372-counting-the-number-of-times-a-number-appears-next-to-the-same-one-in-a-row#comment_717202

## Andrei Bobrov (view profile)

Direct link to this comment:https://in.mathworks.com/matlabcentral/answers/468372-counting-the-number-of-times-a-number-appears-next-to-the-same-one-in-a-row#comment_717203

Sign in to comment.