Counting the number of binary toggles
4 views (last 30 days)
Say I have a binary array B of size n.
B_1 = [1 1 1 0 0 1 0 1 0 0 1];
B_2 = [1 1 1 1 0 0 0];
I am trying to think up an algorithm that would yield the number of switches(toggles) between 1 to 0 and conversely, 0 to 1.
For instance, with my binary array examples, I would like the result to be '6' for B_1 and '1' for B_2.
This is the code I devised, which entails linearly shifting the original array by 1 position and XOR'ing the shifted array with the original one, thus yielding the number of toggles. My problem is that it only works for certain arrays like B_1, yielding 6. But for arrays like B_2 the result is, erroneously 2:
B = [1 0 1 1 0 0 0 1 1];
B_shifted = circshift(B,1);
toggleArray = xor(B, B_shifted);
toggleCount = length(toggleArray(toggleArray==1)); %this is where I would like to store the desired result
Now I understand the limitations of my code, but I wanted to know if there was a more obvious, simpler, more elegant way that I am missing, or if there is a Matlab function that would do this for me.