MATLAB: Calculating Average Duration/Length in an Array

duration array markov

Hello,
I have an array that contains 1 2 3 which each represents a state i.e) 1=sunny day 2=rainy day 3=cloudy day. The array is about 1 million length.
Example: [3 3 3 1 1 1 1 2 1 1 2 3 3]
I would like to figure out the average duration of each state. For state 1, it would be (4+2/2)= 3 days. For state 2, it would be (1+1/2=)1day. And state 3 it would be (3+2/2)=2.5days
I'm wondering if anyone has any suggestion or tips on how to do this with minimal code.
Cheers, David

Best Answer

The histc function (with help from unique) is probably the easiest option:
W = [3 3 3 1 1 1 1 2 1 1 2 3 3];
bins = unique(W);
k = histc(W,bins);
avg = k./2;