How to store a number with its leading zeros?
Afficher commentaires plus anciens
I have to input a 9 digit code into 'x' and then separate the digits so I can evaluate some conditions, the thing is, the code can start with a zero. However if I input 'x=012345678' MatLab will say x=12345678. I tried n=num2str(x) but it will say n='12345678' no leading zero. This is really stressing. Is there a way it doesn't skip the zero? I heard you can input a number into a variable as a string, then it wouldn't skip the zero. But I really don't know how to do that (this my first week learning MatLab)
1 commentaire
David Fletcher
le 9 Mar 2018
str = input('Enter value ','s')
Enter value 0043321
str =
'0043321'
Réponses (3)
To define x as a character vector:
x = '012345678'
Numeric classes do not store leading zeros, or any formatting information.
Image Analyst
le 10 Mar 2018
Try this:
% Define x as a string with leading zeros.
x = '00012345678'
% Get digits separated:
numbers = x - '0'
You will see
x =
'00012345678'
numbers =
0 0 0 1 2 3 4 5 6 7 8
so your individual digits, including any zeros, are now elements of a numerical vector "numbers" that you can then inspect to "evaluate some conditions".
James Tursa
le 10 Mar 2018
Modifié(e) : James Tursa
le 10 Mar 2018
Another way:
x = your numeric number
the_digits = sprintf('%09d',x)-'0';
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!