0
votes

I have a table which contains the year and the month in a "double" format.

I then create a datenum for each entry in the table:

for j=1:number_of_rows
dates_returns_all_period_monthly(j,10)=datenum([year,month,1]);
end

First of all, is there a way to have the dates on a monthly basis without having to set the day on the datenum command?

Secondly, the previous commands give me values such as 731947 for

I then want to get the date in a date format,

I am trying to run the following command:

dates_returns_all_period_monthly(j,11)=datestr(dates_returns_all_period_monthly(j,10));

but I get an error "Assignment has more non-singleton rhs dimensions than non-singleton subscripts"

How can I fix this? Ideally I would like to have something like January 2004, February 2005, etc.. or 01/2004, 02/2004, something like that, because later on I want to plot with the dates on the x-axis, and I don't want to have 731947 etc. as values.

1
I think you are looking for datetime instead of datenum - GameOfThrows

1 Answers

1
votes

The problem here is that you are trying to put a string output into a matrix array. This won't work: it will try and convert the string to an array of numbers, and your indexing will tell it to try to put your array of numbers into a single matrix location, causing the error that you are seeing.

What you'll need to do if you wish to store them is to create a cell array, which store arbitrary data inside each element location, but require different syntax to access:

text_dates = cell(1,number_of_rows);
for j=1:number_of_rows
    text_dates{j}=datestr(dates_returns_all_period_monthly(j,10));
end

You won't be able to use these directly as part of the plot command however - Matlab needs inputs to plot to be numeric, so strings will not work. What you want to do is create your plot using your numeric values, then access the current axis properties (you can use the gca command to get this) and change the `XTickLabel' properties to the strings you wish, e.g.:

plot(dates_returns_all_period_monthly(:,10),whatever_your_y_values_are);
ax=gca;
set(gca,'XTickLabels',text_dates);