How to test if a number has specific digits in it?

y=input('Input a number')
y=num2str(int)-'0';
if y(1:size(y)) == 1 || 4 || 8
disp ('Your number contains the digits 1, 4 or 8')
else
disp ('Your number does not contain the digits 1, 4 or 8')
end
I am trying to test if a number, of any size, contains the digits 1, 4 or 8. I don't get any error messages but the test doesn't work as it says it contains the digits for numbers like '565'

Answers (1)

Once you convert it to string, use contains function to check if a digit is there.

2 Comments

y=input('Input a number')
y=num2str(y);
if contains(y, '1') || contains(y, '4') || contains(y, '8')
disp ('Your number contains the digits 1, 4 or 8')
else
disp ('Your number does not contain the digits 1, 4 or 8')
end
Replace
y=input('Input a number')
y=num2str(y);
with simpler and safer:
y = input('Input a number','s');
and then simply:
if any(ismember(y,'148'))

Sign in to comment.

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Products

Release

R2020b

Asked:

on 27 Jul 2021

Edited:

on 28 Jul 2021

Community Treasure Hunt

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

Start Hunting!