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

2 次查看(过去 30 天)
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 个评论
Jay Alan
Jay Alan 2018-11-28
编辑:Jay Alan 2018-11-28
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 个评论
Jay Alan
Jay Alan 2018-11-28
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by