function [beta, alpha, err] = linear_regress_stat(y, x)

% [beta, alpha, err] = linear_regress_stat(y, x)
% 
% This function calculates slope, offset and error of linear regression.
% 
% y         - input column vector
% x         - input column vector defining the x-axis
% beta      - slope of linear regression
% alpha     - offset of linear regression
% err       - error of linear regression

%% Prepare the aux. variables
if (nargin < 2 || (isempty(x)))
    x = (0:(length(y) - 1)).';
end

x = x(:);
y = y(:);
n = length(y);

m_x = mean(x);
m_y = mean(y);

%% Calculate slope (beta), offset (alpha) and error of linear regression
beta  = sum((x - m_x).*(y - m_y))/sum((x - m_x).^2);
alpha = m_y - beta*m_x;
err   = (1/(n*(n - 2)))*(n*sum(y.^2) - sum(y)^2 - (n*sum(x.^2) - ... 
    sum(x)^2)*beta^2);