% Example of least-squares fit for amplitude and DC offset of a sine wave.
%
% ELEC 471, R. Kozick

% True values of sine wave amplitude a and DC offset b

a = 2.1;
b = 1.2;

N = 4;    % Number of measurements to process

t = [0.1, 1.5, 4, 5];                 % Time values
errors = [0.1, -0.11, 0.075, -0.15];  % Errors to the voltages

v = a*sin(t) + b + errors;            % Voltage measurements

% Solve 2 x 2 simulataneous equations 
% for the least-squares estimates of a and b

lsp = [sum(sin(t).^2), sum(sin(t)); sum(sin(t)), N] \ [sum(v.*sin(t)); sum(v)];
als = lsp(1);           % Estimate of a
bls = lsp(2);           % Estimate of b

tfit = 0:.1:2*pi;
yfit = als*sin(tfit)+bls;   % Compute the "fit" based on als and bls

plot(t, v, 'o', tfit, yfit, '-')
legend('Data with errors in v', 'Least-Squares Fit')
xlabel('t')
ylabel('v')
axis([0 2*pi -1.5 3.5])
title('LEAST-SQUARES FIT OF SINE WAVE AMPLITUDE AND DC OFFSET')

fprintf('Actual parameter values:  a = 2.1, b = 1.2\n');
fprintf('Least-squares estimates:  a = %f, b = %f\n', als, bls);
