%NLSSR: MATLAB script M-file written to plot 
%sums of squared residuals for some example
%nonlinear fits.
%
%Single parameter, y = sin(px)
%
%GENERATE RANDOM DATA
x = 5*randn(1,5)+2;
p = 2;  %FOR GENERATING Y
y = sin(p*x)+randn(1,5);
avals = linspace(0,5,1000);
for k = 1:length(avals)    
    E1(k) = norm(y - sin(avals(k)*x))^2;
end
plot(avals, E1)
title('SSR for $y(x) = \sin (px)$','Interpreter','latex','Fontsize',16)
xlabel('$p$','Interpreter','latex','Fontsize',14)
ylabel('$E$','Interpreter','latex','Fontsize',14)
%
pause
%Two parameters, y = sin(p1*x)+cos(p2*x)
x = 5*randn(1,25)+2;
p1 = 2; p2 = 3;  %FOR GENERATING Y
y = sin(p1*x)+cos(p2*x)+randn(1,25);
p1vals = linspace(0,5,100);
p2vals = linspace(0,5,100);
for k=1:length(p1vals)
    for j = 1:length(p2vals)
        E2(j,k) = norm(y - sin(p1vals(k)*x) - cos(p2vals(j)*x))^2;
    end
end
[p1grid,p2grid]=meshgrid(p1vals,p2vals);
figure
mesh(p1grid,p2grid,E2);
title('SSR for $y(x) = \sin (p_1 x) + \cos(p_2 x)$','Interpreter','latex','Fontsize',16)
xlabel('$p_1$','Interpreter','latex','Fontsize',14)
ylabel('$p_2$','Interpreter','latex','Fontsize',14)
zlabel('$E$','Interpreter','latex','Fontsize',14)