Will polyfit work with datetime vectors
68 views (last 30 days)
Star Strider on 3 Mar 2016
You would have to convert from the datetime object back to a date number using datnum:
q = now + [0:6]'; % The Next Full Week
dtv = datetime(q, 'Format','yyyy-MM-dd', 'ConvertFrom','datenum');
dnv = datenum(dtv);
To use polyfit optimally in this context, depending on what your resulting datenum vector was, ask it for all three outputs in order to scale and centre your data, then pass them to polyval to produce a vector of correctly fitted points. To display the dates and times on your plot, use the datetick function with the date numbers in the ‘dnv’ vector here.
Adam Danz on 19 Nov 2021
I'm also looking for a solution to this and specifically am interested in the y-intercept of a simple linear fit so I can plot the regression line.
My solution is to specify the datetime that defines the y-axis and convert the dates to days since the base date (or hours, minutes, seconds depending on your temporal scale).
dates = datetime(2000,1,1) + hours(sort(randperm(9000,80)));
data = 5*(1:numel(dates))-2 +rand(1,numel(dates));
basedate = datetime(2000,1,1); % defines y-axis for y-intercept
plot(dates, data, 'o')
% Day from base-date
dayVals = days(dates - basedate)
% Beta coefficients
coefs = polyfit(dayVals, data, 1) % using days-from-basedate
% Now add regression line
regY = polyval(coefs, dayVals([1,end]));
plot(dates([1,end]), regY, 'r--', 'LineWidth', 2)