(* This notebook is designed to compute a Fourier series from actual electrocardiogram (ECG) data. The data is taken from the MIT-BIH Arrhythmia Database on PhysioNet.com. It came from an 84-year-old female.*)

(* Set the working directory ("UserDirectory") to wherever you have placed "ECGsamples.csv"*)
SetDirectory["UserDirectory"];

(*Read in data from "ECGsamples.csv" to a matrix. Remove the first two rows, since they contain text headers. You're left with a two-column matrix, where the first column represents time and the second represents voltage.*)
ECGtemp=Import["ECGsamples.csv"];
ECG=Drop[ECGtemp,2];

(*Extract time and voltage data from ECG.*)
ECGtime=ECG[[All,1]];
ECGvolt=ECG[[All,2]];

(*Plot data.*)
ListPlot[Transpose[{ECGtime,ECGvolt}],AspectRatio->0.2,PlotMarkers->{Automatic, 3}]

(*Take the Fourier transform of the voltage data.*)
fECG=Fourier[ECGvolt];

(*Throw away small complex parts and normalize to get Fourier coefficients.*)
n=Length[fECG];
Cf=Chop[fECG]/Sqrt[n];

(*Define Fourier series to 150 terms. The exponentials have factors of 2/Pi in the exponent to get the period to come out correctly.*)
f[x_]=Sum[Cf[[i]]*Exp[-I*(i-1)*(2/Pi)*x]+Conjugate[Cf[[i]]]*Exp[I*(i-1)*(2/Pi)*x],{i,144}];

Plot[f[x],{x,0,10},AspectRatio->0.2]

(*Display the original ECG figure for reference*)
Import["ECGchart.png"]

(*Now let's zoom in and analyze the convergence.*)
Manipulate[Plot[Sum[Cf[[i]]*Exp[-I*(i-1)*(2/Pi)*x]+Conjugate[Cf[[i]]]*Exp[I*(i-1)*(2/Pi)*x],{i,a}],{x,0,2},PlotRange->{{0,2},{-3.5,2.5}}],{a,1,150}]