# How do i count same consecutive occurrences

62 Ansichten (letzte 30 Tage)
DuckDuck am 23 Okt. 2018
Kommentiert: Bruno Luong am 16 Dez. 2021
Consider I have an array of occurrences
A=[1,1,1,1,1,2,2,2,2,3,3,3,3,2,2,2,1,1,1,1]
I want to find out how many 2 are on each occurrence. The answer should be 4 starting 6th position and 3 starting 14 positions.
Is it possible to do it in a wise Matlab way without many loop complications?
##### 0 Kommentare-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Antworten (3)

madhan ravi am 23 Okt. 2018
Bearbeitet: madhan ravi am 23 Okt. 2018
##### 0 Kommentare-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

Daniel Pare am 5 Nov. 2019
I wanted to count how many time in a row Head or Tail will occure from a random draw and I came up with this.
Let (x) be your vector of observation like x = [1 1 0 1 0 0 0 1]
The result will be: s = [ 2 1 1 3 1]
s=0 ;
j=2;
i=1;
while i < nb_it+1
c=1;
if i == nb_it
s = [ s c];
break
else
while x(i) == x(i+1)
c = c+1;
i = i+1;
if i == nb_it
break
end
end
end
s = [ s c];
i = i+1;
end
s = s(2:end); % to remove the first zero
sum(s) % the sum should be equal to the number of element in (x)
max(s) % This is the maximum of consecutive ocurence from the draw
##### 5 Kommentare4 ältere Kommentare anzeigen4 ältere Kommentare ausblenden
gummiyummi am 3 Aug. 2020
I get an error: Error using horzcat. Dimensions of arrays being concatenated are not consistent.
Can anybody help resolve this?

Melden Sie sich an, um zu kommentieren.

Bruno Luong am 3 Aug. 2020
Bearbeitet: Bruno Luong am 16 Dez. 2021
Example:
A=[1,1,1,1,1,2,2,2,2,3,3,3,3,2,2,2,1,1,1,1]
Code
d = diff([0, A==2, 0]);
startidx = find(d==1)
lgt = find(d==-1)-startidx % EDIT error
Result
startidx =
6 14
lgt =
4 3
##### 4 Kommentare3 ältere Kommentare anzeigen3 ältere Kommentare ausblenden
Bruno Luong am 16 Dez. 2021
@Ayush Meena it's a typo, should be startidx.

Melden Sie sich an, um zu kommentieren.

### Kategorien

Find more on Resizing and Reshaping Matrices 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!