How to count number of ones and zeros in a binary number?

조회 수: 30 (최근 30일)
ASHA PON
ASHA PON 2022년 11월 29일
댓글: ASHA PON 2022년 11월 29일
I am having some set of binary numbers. I need to count the number of ones and zeros in each binary number. If a binary number has even number of ones then the output has to be '1' or it has to be '0'. Thank you in advance.
Example:
A=1100
B=0100
output of A =1
output of B = 0

채택된 답변

Davide Masiello
Davide Masiello 2022년 11월 29일
편집: Davide Masiello 2022년 11월 29일
I will assume that your binary numbers are stored as a character array, which is how Matlab normally works, e.g.
A = dec2bin(20)
A = '10100'
B = dec2bin(21)
B = '10101'
Now in the example above, A has an even and B has an odd number of ones respectively.
your desired output can be easily obtained with
1-mod(nnz(A=='1'),2)
ans = 1
1-mod(nnz(B=='1'),2)
ans = 0
  댓글 수: 3
Davide Masiello
Davide Masiello 2022년 11월 29일
A= [1110, 0111, 0110, 1111];
B = 1-mod(sum(num2str(A') == '1',2),2)
B = 4×1
0 0 1 1
ASHA PON
ASHA PON 2022년 11월 29일
Thank you for the reply. This is what i needed.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Chunru
Chunru 2022년 11월 29일
% if you use char to represent binary numbers
A='1100';
mod(sum(A=='1'), 2) == 0
ans = logical
1
% if you use double to represent binaray numbers, you can do the conversion
% first
A = 1100;
A = num2str(A)
A = '1100'
mod(sum(A=='1'), 2) == 0
ans = logical
1
  댓글 수: 4
ASHA PON
ASHA PON 2022년 11월 29일
Thank you for the reply. Actually i am having an array of 15 binary numbers and i need to apply the above mentioned concept to each numbers.
Example:
A=[ 1110, 0111, 0110, 1111]
Expected output:
B= 0, 0, 1, 1

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by