Will polyfit work with datetime vectors
53 views (last 30 days)
Show older comments
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));
0 Comments
Answers (2)
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.
0 Comments
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)
% Beta coefficients
coefs = polyfit(dayVals, data, 1) % using days-from-basedate
% Now add regression line
regY = polyval(coefs, dayVals([1,end]));
hold on
plot(dates([1,end]), regY, 'r--', 'LineWidth', 2)
axis tight
0 Comments
See Also
Categories
Find more on Calendar in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!