Matlab addtodate function - matlab

I am trying to use "addtodate" function of matlab. Am I correct in observing that it can't be applied to vector of dates ?
If that is the case how do I add an hour to each of the dates in the following vector of dates:
stDt = datenum('2/28/2014');
endDt = datenum('4/29/2014');
interval = (datenum(1987,0,0,1,0,0)-datenum(1987,0,0,0,0,0));
z1 = datenum(stDt):interval:datenum(endDt);
z = datestr(addtodate(z1,1,'hour'));
The last line fails with following error:
??? Error using ==> addtodate at 42
Date number must be a numeric scalar.

datenum in matlab returns a serial date number in units of days. To add an hour to each date in a vector just add 1/24:
z = datestr(z1 + 1/24);

Related

Converting Epoch to Date in Matlab with fractions seconds

I have an array of Epoch times that include fractional (nanoseconds). I have reviewed Converting Epoch to Date in Matlab but still cannot seem to convert to the correct date. I must be missing something simple.
Example data:
1548348497.191261
I am using the code in the link above.
time_unix_nanos = 1548348497.191261;
millis = round(time_unix_nanos);
nanos = time_unix_nanos - 1e6 * millis;
time_matlab = round(864e5 * (millis - datenum('1970', 'yyyy')));
s = [datestr(time_matlab, 'yyyy-mm-dd hh:mm:ss.FFF;), num2str(nanos)];
fprintf('s: = %f\n',s);
Two desired outputs
Full date format: yyyy-mm-dd HH:mm:ss.SSS
Just time format: HH:mm:ss.SSS
Thanks in advance!
It seems you've mistaken the conversion of unixtime to matlab time with matlab time to unixtime.
time_unix_nanos = 1548348497.191261;
millis = round(time_unix_nanos / 1e6); % You had also a /1e6 missing here
nanos = time_unix_nanos - 1e6 * millis;
% The following line converts unix time to matlab time. The line you used was doing the opposite
time_matlab = datenum('1970', 'yyyy') + millis / 864e5;
% First desired date format
s1 = [datestr(time_matlab, 'yyyymmdd HH:MM:SS.FFF;'), num2str(nanos)]
% Second desired date format
s2 = [datestr(time_matlab, 'HH:MM:SS.FFF;'), num2str(nanos)]
gives
>> s1
'19700101 00:00:01.548;348497.1913'
>> s2
'00:00:01.548;348497.1913'

interpolate missing values ( with dates as sample points) in matlab

I am new to Matlab, stuck with understanding data types(especially cell), probably there is an elegant solution I do not know about.
I have a cell which contains other cells with dates:
30/09/2005
30/12/2005
...
30/09/2016
I have also a cell with cells containing corresponding values:
1
5
...
3
I want to interpolate those values for all days/ or working days( better for me).
What I have been thinking to do is:
use datenum to receive numbers corresponding to the dates;
plug these dates( now numbers), corresponding values, and all dates( now numbers) in between them, into interp1.
Seemed a good plan but function
datenum('30/12/2005') = 13297
datenum('30/09/2016') = 13217
gives numbers which can not be used as earlier date is bigger than later one.
You can add any number of days to a datetime.
t = datetime('now') + days(1);
In addition it can give you the amount of days of a duration. Hence:
t0 = datetime('30/09/2005');
tEnd = datetime('30/09/2016');
durationInDays = days(tEnd - t0);
myDates(0) = t0;
for i = 2:durationInDays
myDates(i) = myDates(i-1) + days(1);
end

How to format dates on a plot and remove gap from time

I have the following plot created from this very simple script.
clear;
format long g
Ts = ncread('EURUSD_1 hour_30_D_2015-11-03_02-52-36-PM.nc', 'TimeStamp');
Obs = ncread('EURUSD_1 hour_30_D_2015-11-03_02-52-36-PM.nc', 'Close');
plot(datenum(Ts), Obs);
datetick('x', 20);
However, I get this error:
>> netcdfExample
Error using datevecmx
Date number out of range.
Error in datevec (line 303)
[y,mo,d] = datevecmx(t);
Error in dateTickPicker (line 85)
[y,m,d] = datevec(x);
Error in datetick>bestscale (line 292)
[labels,format] = dateTickPicker(axh,[xmin,xmax],dateform,dateChoice,axVal);
Error in datetick (line 251)
ticks = bestscale(axh,ax,vmin,vmax,dateform,dateChoice);
Error in netcdfExample (line 9)
datetick('x', 20);
>>
When I just try something simple like this
>> formatOut = 'mmmm-dd-yyyy';
>> str = datestr(6.35821236e+17,formatOut,'local')
I get this error. I wonder if these encoded date numbers are wrong?
Error using dateformverify (line 28)
DATESTR failed converting date number to date vector.
Error in datestr (line 194)
S = dateformverify(dtnumber, dateformstr, islocal);
Caused by:
Error using datevecmx
Date number out of range.
The datetimes/close look like this (in the .csv vesion)
9/22/2015 16:15 1.11255
9/22/2015 17:00 1.11305
9/22/2015 18:00 1.112
9/22/2015 19:00 1.1107
9/22/2015 20:00 1.1123
The date is from hourly intra-day data (netcdf format) that I read from a file into Matlab :
As you can see, the x-axis are numbers in 10^17 format instead of System.DateTime from C#. Also, please note that since the markets close and reopen, there is a line joining the plot between when the market closes, and reopens.
How do I:
Get rid of the date gap. I want the data to be next to its neighbor.
Make the x-axis tick marks be something resembling a date/time?
The y axis data has five decimal places of precision. How do I ask the plot to show more precision on the y-axis tick marks?
I sort of figured out a workaround. In the C# program, instead of using a Datetime, I convert the Datetime to a double. Then this program works fine
Ts = ncread('EURUSD_1 hour_30_D_2015-11-03_06-41-44-PM.nc', 'TimeStamp');
Obs = ncread('EURUSD_1 hour_30_D_2015-11-03_06-41-44-PM.nc', 'Close');
plot(Ts, Obs);
datetick('x', 'mm-dd-yy HHPM');
I still don't know how to add precision to the y axis, and how to remove the gaps in time on the x-axis. It is interesting because if I just say
plot(Obs)
The plot looks correct on the y-axis but the x-axis is numbers. If I add
plot(Ts, Obs)
datetick('x', 'mm-dd-yy HHPM');
Then the x-axis is correctly "indexed" by date/time, but I suspect that Matlab is honoring the gaps in time so the plot looks "jumpy" and disconnected.

How to import dates into MATLAB

I am using MATLAB R2015b. I am trying to import a excel file full of dates using xlsread('filename.xls'). The dates looks like the followings:
02/01/1996
03/01/1996
04/01/1996
05/01/1996
08/01/1996
then I want use datevec to separate the day month and year. for date = '02/01/1996'(January 2nd 1996), datevec gives Y= 1996, M = 2, D= 1,H=0 MN=0 S=0. For date '29/12/2000' (Dec 29 2000), datevec gives Y = 35, M=5 D =23 H=0 MN=0 S=0.
I tried to change the date format in excel, but it still does not work. Can anyone let me know how can I fix this please?
DateVector = datevec(DateString,formatIn)
As per the documentation. Set your formatIn correct:
DateString = {'16/09/2007';'14/05/1996';'29/11/2010'};
formatIn = 'dd/mm/yyyy';
datevec(DateString,formatIn)
Since MATLAB is an American program all their defaults are American (hence you're not able to call your colourbar as you want to). You just have to select a different date format.

Using consecutive matrices in Matlab

I'm creating a function to use multiple matrices in an analysis studio.
The matrices are given with the same name with a date reference in the name (month to month and year to year: nov-1956 is matrix5611, dec-1956 is matrix5612, jan-1957 is matrix5712, and so on until the end of 1999.
For each one there should be a comparison between the mean value of each month/year (depending of what area of study are you focused on).
I'm trying to use some loops to vary the name of the input matrix instead of write manually date by date, but a function that helped would be useful.
Any idea or useful function?
If you have your data in different matrices, you can use eval to store the means to some matrix, in this example MeanMatrix, in which Y dimension is year and X dimension is month:
Edit: It's not running number from 5611 but yymm...
Edit: It seems that matrices don't begin from January 1956 but from November 1956.
% add here missing months matrix index strings.
MissingMatricesCellArray = {'5601', '5602', '5603', '5604', '5605', '5606', '5607', '5608', '5609', '5610'};
% MissingmatricesCellArray = {};
for Year = 56:99
for Month = 1:12
NumString = sprintf('%02d%02d', Year, Month);
% calculate and store means only for matrices that are not missing.
if ~(ismember (cellstr(NumString), MissingMatricesCellArray))
MeanMatrix(Year,Month) = mean(mean(eval ([ 'matrix', NumString ])));
end
end
end
Then you can compare the means of months and years the way you wish.
I would prefer to use cell array's for this rather than eval.
for y = 56:99 % for each year
for m = 1:12 % for each month
ind = createYearMonthInd(y,m);
matrix{ind} = ... % whatever you want here (note the curly braces)
end
end
function ind = createYearMonthInd(y,m)
ind = y * 100 + m;