Counting the number of binary toggles
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Karam Elabd
am 10 Nov. 2017
Kommentiert: Karam Elabd
am 10 Nov. 2017
Hello,
Say I have a binary array B of size n.
example arrays:
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.
Thanks!
Karam
0 Kommentare
Akzeptierte Antwort
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!