MATLAB: How to add zeros in fronts of any number in matrix

codemathematics

dten = datenum([1998 1 1 ;2002 12 31]);
[M] = datevec(dten(1):dten(2));
years = M(:,1);
months = M(:,2);
days = M(:,3);
i want to add zeros in front of 1, 2, 3, 4, 5, 6, 7, 8, 9 like this 01, 02, 03, 04, 05, 06, 07, 08, 09 in months and days matrix. how will do this. please help me. thank you in advance.

Best Answer

Asking for this probably you do not want anymore your years, months, days vectors to be numbers but chars. Because you know from basic maths that '01' doesn't exist as type of number.
myCellMonth = cellfun(@(x) num2str(x),num2cell(months),'UniformOutput', false);
idx = cellfun(@(x) numel(x),myCellMonth);
idx = idx==1; % we want to add a leading '0' only in front of 1,2,3,...9
myCellMonth(idx) = cellfun(@(x) strcat('0', x),myCellMonth(idx),'UniformOutput', false)
In the same logic you could reform days and years
Regards