# Will polyfit work with datetime vectors

91 views (last 30 days)
Andy Stevenson on 3 Mar 2016
My independent variable is a datetime vector. My dependent vector is speed. I get this error:
Error using ones CLASSNAME input must be a valid numeric class name.
Error in polyfit (line 59) V(:,n+1) = ones(length(x),1,class(x));

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).
Example:
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)
dayVals = 1×80
10.0000 11.7500 13.7083 20.5000 20.7083 22.8333 23.8750 24.2500 30.6250 30.7917 30.8750 43.1250 44.5417 58.8333 70.3750 76.7500 77.2083 78.1667 80.7500 81.6667 83.2083 83.5000 87.7500 88.6250 96.5417 102.6250 127.2500 127.7083 129.2083 132.8750
% Beta coefficients
coefs = polyfit(dayVals, data, 1) % using days-from-basedate
coefs = 1×2
1.0146 10.7879
regY = polyval(coefs, dayVals([1,end]));
hold on
plot(dates([1,end]), regY, 'r--', 'LineWidth', 2)
axis tight