MATLAB: How to add line of best fit to plot

plotspolyfitscatter plot

I want to add a line of best fit to my plot using the polyfit function. However, the graph turns blank when I integrate polyfit in my code. How can I change it to make polyfit work?
% original graph without line of best fit
rideData; % file that contains arrays of data/numbers for climb and calories

figure(1);
plot(climb, calories, "o");
xlabel('climb');
ylabel('calories');
% new graph with polyfit. it turns blank
rideData; % file that contains arrays of data/numbers for climb and calories
figure(1);
polyfit(climb, calories, "o");
xlabel('climb');
ylabel('calories');

Best Answer

You are not accepting the coefficients from polyfit() - they basically are thrown away. Even if you did do
coefficients = polyfit(climb, calories, 2);
you still need to compute the fitted values, like
numFitPoints = 1000; % Enough to make the plot look continuous.
xFit = linspace(min(climb), max(climb), numFitPoints);
yFit = polyval(coefficients, xFit);
hold on;
plot(xFit, yFit, 'r-', 'LineWidth', 2);
grid on;
See attached demo, which produces the plot below.