Reputation: 47
I would like to keep the seconds uniform in my time vector using Matlab.
for example in my data the time vector is
01-01-2007 14:18:30; 01-01-2007 14:19:30;01-01-2007 14:20:38;01-01-2007 14:21:28
and so on.. I want it to keep it uniform to
01-01-2007 14:18:30; 01-01-2007 14:19:30;01-01-2007 14:20:30;01-01-2007 14:21:30.
Any help would be greatly appreciated Thanks. S.S
Upvotes: 0
Views: 43
Reputation: 45752
So it depends on how your dates are stored
As a string array:
s = ['01-01-2007 14:18:30';
'01-01-2007 14:19:30';
'01-01-2007 14:20:38';
'01-01-2007 14:21:28']
s(:,end-1:end)= repmat('30', size(s,1),1)
or if for some reason you don't want to use repmat
(this might be faster), you can take advantage of the fact that Matlab automatically broadcasts scalars:
s(:,end-1)='3';
s(:,end)= '0';
or as a cell array of strings:
c = {'01-01-2007 14:18:30';
'01-01-2007 14:19:30';
'01-01-2007 14:20:38';
'01-01-2007 14:21:28'}
cellfun(@(x)([x(1:end-2),'30']), c, 'uni', false)
or if you have your dates as numbers then
s = ['01-01-2007 14:18:30';
'01-01-2007 14:19:30';
'01-01-2007 14:20:38';
'01-01-2007 14:21:28']
n = datenum(s, 'dd-mm-yyyy HH:MM:SS')
%// Note that n will store numbers in units of days, so to round off to the nearest 30 seconds we must round to multiples of 1/(# of 30 seconds per day)
k = 2*60*24; %//The number of 30 seconds per day
round(n*k)/k
or with any of them, you can covert to a date vector:
v = datevec(s, 'dd-mm-yyyy HH:MM:SS')
or
v = datevec(n)
where s
or n
are defined as above. Now you can simply go
v(:,end) = 30;
and then use datestr(v)
or datenum(v)
to go back.
Upvotes: 1
Reputation: 1189
In the data strings the last the seconds are always the last two places in the string so you can just replace them by using:
date_string='01-01-2007 14:18:28';
uni_seconds = '30';
date_string(end-1:end)=uni_seconds
The last line states that the last two places (end-1 and end) are to be replaced by the variable uni_seconds which is the string containing the seconds you want to set.
Upvotes: 1