fit data with x axis already formatted with dateticks() MATLAB
8 views (last 30 days)
Show older comments
I have been at this for hours, i feel like the simple problems take the longest which is annoying. I cannot seem to fit a curve to my data, i've tried fit(), polyval(), and I cannot get them to work. I think the problem is, my x axis is in months, not really numbers so the functions hate me right now. Here is my code:
startDate = datenum('01-01-1985');
endDate = datenum('12-31-1985');
month = linspace(startDate,endDate,12);
waterLevel1985 = [75.2 75.3 75.4 75.6 75.7 75.75 75.6 75.5 75.3 75.25 75.2 75.25];
p = polyfit(month,waterLevel1985,4); %error is here apparently...
x = 1:0.5:12;
bestFit = polyval(p,x);
plot(month,waterLevel1985,x,bestFit)
ax = gca;
ax.XTick = month;
datetick('x','mmm','keepticks')
When i plot, I get a graph with jan feb mar apr....etc as my x axis, and the water level values for1985 on my y axis. If I just put plot (month, waterlevel1985, 'r+') I don't get a fitted curve to my data (which looks closest to a 4th degree polynomial). Please help me do this, I cannot figure it out!
EDIT: I've even tried putting [1:1:12] in the polyfit function instead of month and it still won't work. I've been fooling around with polyfit and polyval but they won't work for me. I've even tried the following:
startDate = datenum('01-01-1985');
endDate = datenum('12-31-1985');
month = linspace(startDate,endDate,12);
waterLevel1985 = [75.2 75.3 75.4 75.6 75.7 75.75 75.6 75.5 75.3 75.25 75.2 75.25];
p = polyfit([1:1:12],waterLevel1985,4);
x = 1:0.5:12;
bestFit = polyval(p,x);
plot(month,waterLevel1985,'r+')
hold on
plot(x, bestFit)
hold off
ax = gca;
ax.XTick = month;
datetick('x','mmm','keepticks')
0 Comments
Answers (1)
Chad Greene
on 30 Nov 2015
The way you define months is incorrect. You're actually just picking 12 datenums spaced evenly throughout the year. If you want months, get them by by:
t = linspace(startDate,endDate,12);
[year,month,day] = datevec(t);
See Also
Categories
Find more on Calendar in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!