Assuming you have the data plotted in a
, and that you also have the data saved to variables t
and y
, you can add a linear fit to the plot using linspace
function in Matlab with the following code:
main.m236 chars9 lines
In this example linspace
is used to generate a linearly spaced vector tfit
, which goes from 0 to 10, with 100 equally spaced points. The polyfit
function is used to calculate the linear regression coefficients of the data in t
and y
, and polyval
is used to evaluate the linear regression line at each point in tfit
. Finally, the plot
function is called to plot the linear fit on top of the existing plot with color 'r'
.
Note that the hold on
and hold off
commands are used to make sure that the original data is not overwritten by the new plot.
gistlibby LogSnag