how do i verify input is only zeros and 1's

21 views (last 30 days)
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

Accepted Answer

Guillaume
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 '))
  1 Comment
rick o'brien
rick o'brien on 16 Oct 2015
thank you very much guys for your help i've been trying to figure this out all night. the format all(ismember(number, '01')) solved the problem

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!