%% Polynomial regression. Generate a some data for a saturable curve model. Add normally distributed noise. Fit with a 2nd order polynomial

%% Specify model parameters
ymax = 1;
tau = 3;

%% Generate some data
t = (1:10)';
yTrue = ymax*(1-exp(-t/tau));

%% Add normal error to simulate experimental noise
NoiseStd = 0.1; % The standard deviation of the noise
err = NoiseStd*randn(length(t), 1);
yExpt = yTrue + err;

%% Fit with a 2nd order polynomial. Create design matrix
A = [ones(size(t)) t t.^2];

%% Solve normal equation using the MATLAB backslash operator
betaHat = A \ yExpt

%% Plot data and fit
plot(t, yExpt, 'ro', 'MarkerSize', 8)
hold on
tFit = (1:0.1:10)';
yFit = [ones(size(tFit)) tFit tFit.^2]*betaHat;
plot(tFit, yFit, 'b-', 'LineWidth', 2)
plot(tFit, ymax*(1-exp(-tFit/tau)), 'b--', 'LineWidth', 1)
xlim([0, 11])
ylim([0, 1.1])
xlabel('x')
ylabel('y')
grid on
legend('Data', 'Polynomial fit', 'True function', 'Location', 'NW')
