how do i verify input is only zeros and 1's
21 views (last 30 days)
Show older comments
i am trying to figure out how to check if a number entered by a user is only zeros and ones (checking if its binary). I am not allowed to use a table or matrix
this is what I have, but doesn't seem to work
number = input('please enter a number:', 's')
if all(ismember(number,['0' '1'])) fprintf('this is a binary number.'); else fprintf('this is not a binary number.'); end
0 Comments
Accepted Answer
Guillaume
on 16 Oct 2015
"It does not seem to work" In what way?
>>number = '1100111';
>>all(ismember(number, '01'))
ans =
1
>>number = '123'
>>all(ismember(number, '01'))
ans =
0
Star is right that ['0' '1'] is the same as '01', but if you want to ensure that the characters entered are only '0' or '1', your if statement is correct.
My guess is that it "does not work" because you also put some spaces in your string, eg. '0 1 0 1 1 0'. If you want t allow this format:
all(ismember(number, '01 '))
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!