How to: Count length of identical consecutive elements in an array
Show older comments
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 Comment
Answers (1)
KSSV
on 28 Nov 2018
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'});
Categories
Find more on Calendar 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!