% Initialization steps.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
x = [0 6.7 13.4 18.7 22.8 27]
y = [580 495 445 365 350 340]
% Demo to illustrate how to use the polyfit routine to fit data to a polynomial
% and to use polyval() to get estimated (fitted) data from the coefficients that polyfit() returns.
% Demo first uses a quadratic fit via polyfit()%============= QUADRATIC FIT ===================================
% Now we have sample, noisy y values that we will fit a curve through.
% Plot the training set of data (our noisy y values).
plot(x, y, 'ro', 'MarkerSize', 8, 'LineWidth', 2);
grid on;
xlabel('X', 'FontSize', fontSize);
ylabel('Y', 'FontSize', fontSize);
title('Linear Fit', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
% Do the regression with polyfit. Fit a quadratic curve through the noisy y values.
coefficients = polyfit(x, y, 2)
% Make fit. It does NOT need to have the same
% number of elements as your training set,
% or the same range, though it could if you want.
% Make 500 fitted samples going from the min x to the max x.
xFit = linspace(min(x), max(x), 500);
% Get the estimated values with polyval()
yFit = polyval(coefficients, xFit);
% Plot the fit
hold on;
plot(xFit, yFit, '.-', 'LineWidth', 2);
legend('Training Set', 'Fit', 'Location', 'Northeast');