
function [alpha beta] = fitSigmoid(x, y)
%
% fitSigmoid: Fits a sigmoid curve through the points (x,y)
%
%   This function accepts as input two vectors x and y that represent the
%   (x,y) co-ordinates of points through which we wish to fit a sigmoid
%   curve. It then performs non-linear regression to determine the value of
%   parameters alpha and beta which produces the best fit. The final values
%   of alpha and beta are returned.
%
%   USAGE: [alpha beta] = fitSigmoid(x, y);
%

% If the user didn't click on any points, there is no need to perform any
% regression; we use the default value of alpha and beta in this case.
if (isempty(x))
    alpha = 128;
    beta = 25;
    return;
end

% Add the points (0, 0) and (255, 255) to get a better fit
x = [0; x; 255];
y = [0; y; 255];

% Carry out the regression and return alpha and beta
coeffs = nlinfit(x, y, @sigmoid, [128 25]);
alpha = coeffs(1);
beta = coeffs(2);

end


function y = sigmoid(params, x)
%
% sigmoid: Computes the value of the sigmoid function
%
%   This function computes the value of the sigmoid function with the
%   specified values for alpha and beta, at the set of points defined by
%   the vector x. The corresponding vector of y values is returned.
%
%   USAGE: y = sigmoid([alpha beta], x);
%

y = 255 ./ (1 + exp((params(1) - x) / params(2)));

end