add to the plot in (a) a linear fit to the data for time (tfit) from 0 to 10 using linsapce function in matlab

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.m
% Generate the linear fit
tfit = linspace(0, 10);
yfit = polyval(polyfit(t, y, 1), tfit); % y = p1*t + p2, p1 is the slope, p2 is the y-intercept

% Plot the linear fit on top of the existing plot
hold on
plot(tfit, yfit, 'r')
hold off
236 chars
9 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.

related categories

gistlibby LogSnag