MATLAB: How can i compute a running frequency of 1s in a vector

computing running frequencyfrequency of 1s in a vector

Let vector b = [0 1 0 1], then the running frequency of 1's is runningFrequency = [0 0.5 0.3333 0.5] because the frequency of 1's until (and including) the first bit is 0, the frequency of 1's until the second bit is 1/2, the frequency of 1's until the third bit is 1/3, the frequency of 1's until the fourth bit is 4/2 = 1/2. I used this code and (arrayfun) function to apply to whole vector but it shows only the 4th frequency of 1s in the whole output vector like = [0.5 0.5 0.5 0.5].
function freq = ComputeRunningFrequency(~)
for z=1:1:4
sumofones=sum(y(:) == 1);
freq=sumofones/z;

Best Answer

You are close, however you may be over-thinking it.
This works:
b = [0 1 0 1];
Out = cumsum(b)./(1:numel(b))
Out =
0 0.5000 0.3333 0.5000
Related Question