MATLAB: How to get the average duration for consecutive states

analysisconsecutive numbersdata acquisitiondata extractiondatabase

I wanted to know if there is a way to get the average duration of a state. Attached is a .mat data file with 3 different states indicated with 1, 2 and 3. I am trying to find out the average duration for each of these, if the column is the time(1000 sec) then what's the average duration for each of them, or how many consecutive states are there for specified amount of seconds: 1s in 1sec,1s in 2 sec, 1s in 4 sec,.. 1s in 256 sec,..etc. So if there was a consecutive 1,1,1,1 then that would be one round added to the 4 seconds.
I assumed I need to use histogram bin counts but I don't know how to write the code myself. Or just finding out how many times times it switches from state 1 to state 3.

Best Answer

You want to do some kind of run-length encoding, for which there are many tools available on the File Exchange.
I point you to my own function RUNINDEX, which you can download here:
Score = [1 1 1 2 2 3 1 1 3] % small example
[~, RLE] = runindex(Score) % RLE is the run-length encoding of Score, see the help
% In short: RLE(k,:) = [value of the k-th run, start index of this run, length of this run]
% To get the average for each unique value of Score, you can use, for instance, arrayfun:
Average = arrayfun(@(x) mean(RLE(RLE(:,1)==x,3)), unique(Score))