How to adjust the time digits in this code?
2 views (last 30 days)
Show older comments
Mohamed Nedal
on 12 Feb 2020
Edited: Mohamed Nedal
on 14 Feb 2020
Hello,
I wrote the following code to create a time vector between 13:45 and 14:15 with one minute step.
t1 = datetime(2016,5,4,13,45,0);
t2 = datetime(2016,5,4,14,15,0);
t = t1:minutes(1):t2;
t = t';
[h,m] = hms(t);
for i = 1:length(t)
if m(i) == 0 || 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9
time_axis{i} = sprintf('%d:0%d',h(i),m(i));
else
time_axis{i} = sprintf('%d:%d',h(i),m(i));
end
end
clear i;
time_axis = time_axis';
But the problem is that it adds a wrong zero in th minutes part like this.
'13:045'
'13:046'
'13:047'
.
.
'14:00'
'14:01'
'14:02'
'14:03'
.
.
'14:010'
'14:011'
.
.
How can I fix this?
Many thanks,
Mohamed
0 Comments
Accepted Answer
fred ssemwogerere
on 12 Feb 2020
Hello, this should correct your problem. Where the comments are, is where i have made changes. The rest of your code remains the same
t1 = datetime(2016,5,4,13,45,0);
t2 = datetime(2016,5,4,14,15,0);
t = t1:minutes(1):t2;
t = t';
[h,m] = hms(t);
for i = 1:length(t)
if m(i) == 0 || 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9
% specify the minimum width on both the hour and minute side as "2" but with a leading zero on the minute side
time_axis{i} = sprintf('%2d:%02d',h(i),m(i));
else
% specify the minimum width on both the hour and minute side as "2", but with a leading zero on the minute side
time_axis{i} = sprintf('%2d:%02d',h(i),m(i));
end
end
clear i;
time_axis = time_axis';
4 Comments
More Answers (0)
See Also
Categories
Find more on Logical 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!