Counting the number of binary toggles

2 ビュー (過去 30 日間)
Karam Elabd
Karam Elabd 2017 年 11 月 10 日
コメント済み: Karam Elabd 2017 年 11 月 10 日
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

採用された回答

Walter Roberson
Walter Roberson 2017 年 11 月 10 日
nnz(diff(B_1))
  1 件のコメント
Karam Elabd
Karam Elabd 2017 年 11 月 10 日
lol nice, thanks Walt!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by