How to adjust the time digits in this code?

3 views (last 30 days)
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

Accepted Answer

fred  ssemwogerere
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
Mohamed Nedal
Mohamed Nedal on 13 Feb 2020
ismember(m(i),0:9)
That's even better and elegant. Thank you very much
Mohamed Nedal
Mohamed Nedal on 14 Feb 2020
Edited: Mohamed Nedal on 14 Feb 2020
One more question please.
If I have this
time_axis = ['13:45'
'13:46'
'13:47'
'13:48'
'13:49'
'13:50'
'13:51'
'13:52'
'13:53'
'13:54'
'13:55'
'13:56'
'13:57'
'13:58'
'13:59'
'14:00'
'14:01'
'14:02'
'14:03'
'14:04'
'14:05'
'14:06'
'14:07'
'14:08'
'14:09'
'14:10'
'14:11'
'14:12'
'14:13'
'14:14'
'14:15'];
ax.XTick = [0,240,480,720,960,1200,1440,1680,1920,2160,2400,2640,2880,3120,3360,3600,...
3840,4080,4320,4560,4800,5040,5280,5520,5760,6000,6240,6480,6720,6960,7200];
ax.XTickLabel = time_axis;
t = [2842.6053
3185.8029
3464.6509
3722.0492
4143.8962
4508.5437
4894.6410
5409.4374
5816.9846
6145.8823];
How can I find at which time_axis (or XTickLabel) is t (in the format hh:mm:ss)?

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!