4
votes

I have stock price data with associated dates, stored in column vectors with matlab-formatted datenums.

I often need to do loops or lookups over dates, which as of now i realize using 'external bookkeeping', such as

for i = 1:length(dates)
    thisDate = dates(i)
end

or, even worse

iDate = find(dates == thisDate, 1)

I usually have to do very similar operations, so I would like to build a dates-object that encapsulates this functionality for me. It is trivial to do this by using public properties, such as

dates.datenum(i)
dates.datestr(i)
dates.findOneYearEarlier(i)

etc.

BUT

I need to be able to access the vector directly to maintain compatibility.

Thus, a direct access to my dates-object needs to result in a valid datenum. Example:

dates(i) == 730910              % right now
dates.datenum(i) == 730910      % how I'm able to do it

I need both to work at the same time. Is there any way to accomplish this in matlab?


I came up with a few ideas, but I'm not sure how fruitful they are:

  • instead of having an object that manages all dates, have just one date per object and then make a vector of those objects. Probably painfully slow, and difficult to build lookups...

  • just extract a vector of datenums wherever required, and feed it into the old code. As the old stuff continually get updates, this complicates things, instead of making it easier.

  • Extend the vector-class somehow, but I have absolutely no idea where to start with that.

Thanks for your ideas!

1

1 Answers

2
votes

You can directly subclass double:

classdef myDateContainer < double

    methods
        % Constructor
        function this = myDataContainer(in)
            if nargin<1 || isempty(in)
                % default: zero
                in = 0;
            end
            this = this@double(in);
        end

        % add datestring functionality
        function str = datestring(this)
            dbl = double(this); %# cast to double to get at the value
            str = datestr(dbl); %# convert
        end
    end
end

To use:

date = myDateContainer(1:100);
date(3:5).datestring()