%%
clear
close all
clc

%% Linear Example
clear 
close all
clc
A = [ones(5,1) (1:5)'];
b = [.9 1.9 3.2 4.1 4.8]';
xs = A\b
plot(1:5,b,'.','MarkerSize',25)
hold on, plot(1:5,xs(2)*(1:5)+xs(1),'LineWidth',2)
set(gcf,'Color','w')
set(gca,'FontSize',20)
box off


%% Exponential example
clear
close all
clc

x = [1 2 3 4 5]';
b = [1.38 3.33 4.63 7.38 12.32]';

% linear fit
plot(x,b,'.','MarkerSize',25)
A = [ones(5,1) (1:5)'];
xs = A\b;
hold on, plot(1:5,xs(2)*(1:5)+xs(1),'LineWidth',2)
set(gcf,'Color','w')
set(gca,'FontSize',20)
box off

bhat =A*xs;
fprintf('Error for linear fit: %g\n',norm(b-bhat))

% log fit
blog = log(b);
xslog = A\blog;
m = exp(xslog(1));
beta = xslog(2);

hold on,plot(x,m*exp(beta*x),'LineWidth',2)
fprintf('Error for log fit: %g\n',norm(b-m*exp(beta*x)))



%% Cubic polynomial
clear 
close all
clc
x=-10:10;
b = (ones(size(x))+x.^2+x.^3)';
b = b+5*randn(size(b));
plot(x,b,'.','MarkerSize',25)
A = [ones(length(x),1) x' (x.^2)' (x.^3)'];
xs = A\b
hold on, plot(x,xs(1)+xs(2)*x.^1+xs(3)*x.^2+xs(4)*x.^3,'LineWidth',2)
set(gcf,'Color','w')
set(gca,'FontSize',20)
box off










