bookeraward1
bookeraward1

Reputation: 21

convert number format to time format in matlab

I have a data for 1 hour plotted. My time axis right now is in number form

1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0

I want to change it to time format like

8:00,8:15,8:30,8:45,9:00

where I can define the start time, end time and the time interval.

I tried using datetick and datenum but its not working for me. My time data is a vector with 60000 elements (size 1*6000) and my other measurement vector is also of the same size.

Upvotes: 1

Views: 567

Answers (1)

jez
jez

Reputation: 15369

For maximum control you can do it by hand:

% Plot data
hours = linspace( 0, 2, 6000);  % time base for plot
data = randn( size( hours ) );  % data for plot
plot( hours, data )

% Compute tick positions
tickPos = min( hours ) : 0.25 : max( hours );                  % every quarter hour from start to finish
timeZero = datenum( 2015, 01, 09, 08, 00, 00 );                %  measure from 8:00 this morning
timeStamps = timeZero + tickPos / 24;                          % datenum returns a value in units of days, so divide tickPos by 24 to convert from hours to days
timeStampStrings = cellstr( datestr( timeStamps, 'HH:MM' ) );  % or whatever format seems best
set(gca, 'xlim', hours( [ 1 end ] ), 'xtick', tickPos, 'xticklabel', timeStampStrings )

...but the correct way to use datetick would be to ensure that the plot's x axis is in datenum units:

plot( timeZero + hours / 24,  data )
datetick( 'x', 'HH:MM' )

Upvotes: 3

Related Questions