How do i count same consecutive occurrences

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?

답변 (3개)

Daniel Pare
Daniel Pare 2019년 11월 5일

0 개 추천

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

Or you could do:
s = diff([0, find(diff(x)), numel(x)]);
and be done...
Stephen23
Stephen23 2019년 11월 5일
편집: Stephen23 2019년 11월 5일
Or similarly:
>> s = diff(find([1,diff(x),1]))
s =
2 1 1 3 1
Daniel Pare
Daniel Pare 2019년 11월 5일
Awesome, and this way takes way less time than doing many loop.
Thanks
giannit
giannit 2020년 4월 23일
That one line command is amazing, many thanks!
gummiyummi
gummiyummi 2020년 8월 3일
I get an error: Error using horzcat. Dimensions of arrays being concatenated are not consistent.
Can anybody help resolve this?

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

Bruno Luong
Bruno Luong 2020년 8월 3일
편집: Bruno Luong 2021년 12월 16일

0 개 추천

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

gummiyummi
gummiyummi 2020년 8월 3일
I still get the same error...
Bruno Luong
Bruno Luong 2020년 8월 3일
편집: Bruno Luong 2020년 8월 3일
@As Sc: Can you tell if your A is a row vector? column vector? Something else?
Please type
class(A)
size(A)
then report the result. A is your array.
Ayush Meena
Ayush Meena 2021년 12월 15일
@Bruno can you please tell me what is idx here?
Bruno Luong
Bruno Luong 2021년 12월 16일
@Ayush Meena it's a typo, should be startidx.

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

카테고리

도움말 센터File Exchange에서 Performance and Memory에 대해 자세히 알아보기

제품

질문:

2018년 10월 23일

댓글:

2021년 12월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by