# Fourier fit

From Rizzo_Lab

function [Yp, Parm] = fourier_fit(Ye,X,N) % written by Trent E. Balius % Robert C. Rizzo Research Group % Stony Brook University % syntax: [Yp,Parm] = fourier_fit(Ye,X,N) % Yp is the predicted Y values % Parm is the parameter set = 2*N + 1 % Parm = {V,A1,B1,A2,B2} % f(x) = V(1) + sum(i=1:N){A1(i)*cos(i*x)+B1(i)*sin(i*x)} % Ye is the Y value from the data % X is the X value from the data % N is the number over which sum is calculated % uses fmincon input = rand( (2*N + 1),1); %intial guess lb = -1000*ones(2*N + 1,1); % lower bound ub = 1000*ones(2*N + 1,1); % upper bound [Parm,f] = fmincon(@objective_function,input,[],[],[],[],lb,ub,[],[],Ye,X); Yp = fourier_series(Parm,X); function [val] = objective_function(Parm,Y,X) Yp = fourier_series(Parm,X); %[Y,Yp] val = sum((Y-Yp).^2); return function [Yp] = fourier_series(Parm,X) %whos % f(x) = V(1) + sum(i=1:N){A1(i)*cos(i*x)+B1(i)*sin(i*x)} Yp = Parm(1)*ones(size(X)); for i = 2:length(Parm) if (mod(i,2) == 0) % i is even Yp = Yp + Parm(i)*cos(i*X); else % i is odd Yp = Yp + Parm(i)*sin(i*X); end end return