Question:
How do I add leading zeros to a number in Matlab?
D
2009-03-04 13:28:15 UTC
I'm working in matlab and I need integers produced by a certain loop to have leading 0s so that the number is from 000 to 365. I'm then going to use num2str to get it into a string and concatenate it to a bunch of other text that will create a filename according to a formula. I'm having trouble getting the leading 0s to stay in the number for example if I were to type

> 001
ans = 1

would be the response. Any help would be greatly appreciated. Thank you.
Three answers:
space-saver
2009-03-04 14:01:59 UTC
MATLAB will always traslate 01, 001 etc. into '1'. The best way to do it, if you are aiming for what I think you are, is to include the leading zeros in the strcat command, e.g.



a = 1:365

b = '00'

c = strcat(b,num2str(a),'other text')



EDIT: Actually, if you only want the '00's for single digits, you'll need an if statement, or you could just have 3 separate lines for single digits, double digits and triple digits, where you add 2, 1 or no '0's
peggy
2016-10-01 11:15:08 UTC
Zeros Matlab
anonymous
2013-12-03 15:13:01 UTC
You can call num2str() like this: num2str(number,format)



So to accomplish what you want:



num2str(number,'%03d');



If you want a different number of leading zeros, change the 3.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...