MATLAB: Count number of changes to 1

binarycountingMATLAB

Hi, I have got a binary vector which looks like this: vec = [0 0 0 1 1 0 0 0 0 1 1 1 1 1 1 0 0 1 1 1 1 0 0 0 0 0 1 1 1 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 1 0 0 0 ] I would like to know how many times it changes to 1. In this case six times.
I have tried it by first counting the number of changes: r=sum(abs(diff(vec))) and then devide it by 2. This will work when I have got an equal number of changes to 1 and changes to 0, but this is unfortunately not always the case.
What is the best way to do solve this in matlab?
Many thanks.

Best Answer

Thank you both, but I still have one problem. I have also got binary vectors which start with a 1 like: v= [1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 0] and I want to get eventually the number of streaks of the number 1 (in this case 3). When I determine the number of changes the first streak of 1's isn't counted. How can I solve this problem?
Thanks in advance.