How to test if a number has specific digits in it?
Show older comments
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)
Yongjian Feng
on 27 Jul 2021
0 votes
Once you convert it to string, use contains function to check if a digit is there.
2 Comments
Yongjian Feng
on 27 Jul 2021
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'))
Categories
Find more on Construct and Work with Object Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!