Vectorising Date Array Calculations

date, matlab

Solution

To add `n` years to a date `x`, you do this:

y = addtodate(x, n, 'year');

However, `addtodate` requires the following:

- `x` must be a scalar number, not a string.

- `n` must be a scalar number, not a vector.

Hence the errors you get.

I suggest you use a loop to do this:

CurveLength = 30;
t = zeros(CurveLength, 1);
t(1) = today; % # Whatever today equals to...
for ii = 2:CurveLength
    t(ii) = addtodate(t(1), ii - 1, 'year');
end

Now that you have all your date values, you can convert it to strings with:

datestr(t);

And here's a neat one-liner using `arrayfun`;

datestr(arrayfun(@(n)addtodate(today, n, 'year'), 0:CurveLength))

Problem

I simply want to generate a series of dates 1 year apart from today. I tried this ``` CurveLength=30; t=zeros(CurveLength); t(1)=datestr(today); x=2:CurveLength-1; t=addtodate(t(1),x,'year'); ``` I am getting two errors so far? ??? In an assignment A(I) = B, the number of elements in B and Which I am guessing is related to the fact that the date is a string, but when I modified the string to be the same length as the date dd-mmm-yyyy i.e. 11 letters I still get the same error. Lsstly I get the error ??? Error using ==> addtodate at 45 Quantity must be a numeric scalar. Which seems to suggest that the function can't be vectorised? If this is true is there anyway to tell in advance which functions can be vectorised and which can not?

Original source