MATLAB: How to find the duration of a number in an array

arrayduration

Given the array
c=[3 3 3 5 5 6 7 8 1 1 3 3 3 0 0 0 4 4 4 5 6 7 8 3 3 3 9 10 3];
I am trying to find the average duration of each number in this array. For example, I am looking to find the average duration for 3 in this array. I know that 3 occurs 10 times but is grouped into 4 separate occurrences. I want the output to be the average duration for 3…which is 2.5. please help!

Best Answer

c = c(:);
ii = [true;diff(c)~=0];
i2 = diff([find(ii);numel(ii)+1]);
[a,b,c0] = unique(c(ii),'first'); % in new version of MATLAB:
[~,jj] = sort(b); %


[~,j1] = sort(jj); % [a1,~,c1] = unique(c(ii),'stable');
a1 = a(jj); %
c1 = j1(c0); %
out = [a1,accumarray(c1,i2,[],@mean)];
or with sorting
ii = [true;diff(c)~=0];
i2 = diff([find(ii);numel(ii)+1]);
[a,~,c0] = unique(c(ii));
out1 = [a,accumarray(c0,i2,[],@mean)]