clear all; close all;

filename = "0p6.csv";   
f = 0.1;                    
Fs = 960;                  

data = readmatrix(filename);

V = data(:,2);             
N = length(V);

t = (0:N-1)'/Fs;           

% Remove DC offset
V_ac = V - mean(V);

% Fit sine wave
w = 2*pi*f;
sine_model = @(b,t) b(1)*sin(w*t + b(2));
beta0 = [range(V_ac)/2, 0];

beta = nlinfit(t, V_ac, sine_model, beta0);

phase_deg = rad2deg(beta(2));
fprintf("Phase Lag = %.2f degrees\n", phase_deg);

% Plot fit
t_fit = linspace(min(t), max(t), 2000);
V_fit = beta(1)*sin(w*t_fit + beta(2));

figure;
plot(t, V_ac, 'b'); hold on;
plot(t_fit, V_fit, 'r', 'LineWidth', 2);
xlabel("Time (s)");
ylabel("Voltage (AC)");
title(sprintf("%.2f Hz,Phase Lag = %.2f degrees",f, phase_deg));
legend("Measured", "Fit");
grid on;

