MATLAB: How to display trendline equation on the plot

trendline equation display

Hi
I got the trendline using polyfit() and polyval(). and use plot() to the plot the trendline.
Now my question is how to display the trendline equation onto the plot? Thanks
here are the code for plotting trendline fittedlinecrossplot=polyfit(xdata_crossplot,ydata_crossplot,trendlinepolynomialcoeff); ydata_crossplot_trendline=polyval(fittedlinecrossplot,xdata_crossplot_trendline); hp=plot(hrightsubplot,xdata_crossplot_trendline,ydata_crossplot_trendline,'–g','linewidth',2,'DisplayName',legendlabel_trendline);

Best Answer

ok, I got it now.
here are my codes,
fittedlinecrossplot=polyfit(xdata_crossplot,ydata_crossplot,trendlinepolynomialcoeff); ydata_crossplot_trendline=polyval(fittedlinecrossplot,xdata_crossplot_trendline);
trendlineequationcoeffnum=length(fittedlinecrossplot);
switch trendlineequationcoeffnum
case 2 % means it has slope and intercep 2 numbers
trendlineequationstring=sprintf('y=%.3f x+%.3f',fittedlinecrossplot(1),fittedlinecrossplot(2));
case 3
trendlineequationstring=sprintf('y=%.3f x^2+%.3f x+%.3f',fittedlinecrossplot(1),fittedlinecrossplot(2),fittedlinecrossplot(3));
case 4
trendlineequationstring=sprintf('y=%.3f x^3+%.3f x^2+ %.3f x+%.3f',fittedlinecrossplot(1),fittedlinecrossplot(2),fittedlinecrossplot(3),fittedlinecrossplot(4));
case 5
trendlineequationstring=sprintf('y=%.3f x^4+%.3f x^3+ %.3f x^2+%.3f x+%.3f',fittedlinecrossplot(1),fittedlinecrossplot(2),fittedlinecrossplot(3),fittedlinecrossplot(4),fittedlinecrossplot(5));
end
htrendlinetext=text(pos_rightsubplot(1)+0.5*pos_rightsubplot(3),pos_rightsubplot(2)+0.8*pos_rightsubplot(4),trendlineequationstring,'units','normalized');
htrendlinetext.FontSize=12;
htrendlinetext.FontWeight='bold';
htrendlinetext.Color='r';