%% Nonlinear Least Squares Solution and Residual Norm
% Find the x that minimizes
% \[\sum\limits_{k = 1}^{10} {{{\left( {2 + 2k - {e^{k{x_1}}} - {e^{k{x_2}}}} \right)}^2}} \],
% and find the value of the minimal sum of squares.
% Because lsqnonlin assumes that the sum of squares is not explicitly formed in the user-defined function, the function passed to lsqnonlin should instead compute the vector-valued function
% \[{F_k}(x) = 2 + 2k - {e^{k{x_1}}} - {e^{k{x_2}}}\],
% for k = 1 to 10 (that is, F should have 10 components).
% The myfun function that computes the 10-component vector F appears at the end of this example.
% Find the minimizing point and the minimum value, starting at the point x0 = [0.3,0.4].

x0 = [0.3,0.4];
[x,resnorm] = lsqnonlin(@myfun,x0)

% The resnorm output is the squared residual norm, the sum of squares of the function values.
%
% The following function computes the vector-valued objective function.

function F = myfun(x)
k = 1:10;
F = 2 + 2*k-exp(k*x(1))-exp(k*x(2));
end

% Copyright 2019 The MathWorks, Inc.