MATLAB: Plotting fit and data on the same plot – define endpoint of fit line

plot cfit

Hi – I am plotting a data fit equation and the actual data on the same plot. I can get the basic plot but I cannot get it to look quite like I want.
I need to have the data and the corresponding fit line be the same color and I need the fit line to plot across the entire xrange that is plotted. I have included the relevant portions of the code below.
In the plot that is used in this code (p=plot…), I can get it to work with the exception that the fitline only plots from the first datapoint to the last datapoint (x=7.5 to 52) instead of across the entire range (0 to 55).
If I used the commented out version of the code, it plots across the entire range with the colors, but does not plot the actual data.
Does anybody have any suggestions?
Thank you.
vars = who ('RL*');
figure; rainbow=colormap(hsv(length(vars))); axes('FontSize',20,'FontName','Times New Roman');
hold all; grid on;
for i = 1:length(vars)
...
[fiteqn,rsqr] = fit(RL(:,1),RL(:,2),'poly1','Exclude',outliers);
r2=rsqr.rsquare;
p=plot(fiteqn,RL(:,1),RL(:,2),'.');
% p=plot(fiteqn,'.');
xlim([0 55]);
legendstr(2*i-1,1) = vars(i);
legendstr(2*i,1) = strcat(vars(i),' fit');
set(p,'MarkerSize',12,'Color',rainbow(i,:),'LineWidth',1.5);
...
end
legend(legendstr,'Location','NorthEastOutside');

Best Answer

Maybe this is what you want:
x=sort(rand(10,1));
y=sort(rand(10,1));
[fiteqn,rsqr] = fit(x,y,'poly1');
plot(x,y);
hold on;
fplot(fiteqn,[-1 2]); %replace [-1 2] by the interval you want
Cheers!