How to: Count length of identical consecutive elements in an array

An earlier answer provided to counting identical consecutive elements in an array is as follows (tabulate command added by me)
X = [0 0 0 0 1 1 1 0 1 1 1 1 0 0]; % Sample data
d= [true, diff(X) ~= 0, true]; % TRUE if values change
n = diff(find(d)); % Number of repetitions
tabulate(n)
This code combines the consecutive element lengths of different elements (0s and 1s) in the answer
--> However, am trying to determine length of consecutive elements of "each element type" (not combine consecutive lengths of different element values)
Output content would be something like:
Array entry 0: consecutive length 4, # of occurences=1
Array entry 0: consecutive length 2, # of occurences=1
Array entry 0: consecutive length 1, # of occurences=1
Array entry 1: consecutive length 4, # of occurences=1
Array entry 1, consecutive length 3, # of occurences=1

댓글 수: 1

The following seems to work; any elegant solutions would be greatly appreciated
rr=[ NaN
NaN
NaN
0.0382
-0.0211
0.0252
0.0165
-0.0417
-0.0128
0.0667
-0.0040
-0.0329
-0.0340
0.0172
-0.0085
0.0128
0.0210
-0.0295
-0.0260
0.0260]
rr1=rr>0;
b1 = diff([0 rr1' 0] ==1);
c1 = find(b1==-1) - find(b1==1);
tabulate(c1)
%--
rr0=rr<0;
b0 = diff([0 rr0' 0] ==1);
c0 = find(b0==-1) - find(b0==1);
tabulate(c0)

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

답변 (1개)

KSSV
KSSV 2018년 11월 28일
A = [0 0 0 0 1 1 1 0 1 1 1 1 0 0]; % Sample data
ii = zeros(size(A));
jj = A > 0;
ii(strfind([0,jj(:)'],[0 1])) = 1;
idx = cumsum(ii).*jj;
out = accumarray( idx(jj)',A(jj)',[],@(x){x'});

댓글 수: 1

Thank you very much for the suggestion; am unable to get outputs with your code and will need to analyze further (with my sincere apologies for the delay). Thanks once again.

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

카테고리

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

질문:

2018년 11월 28일

댓글:

2018년 11월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by