Skip to content

Instantly share code, notes, and snippets.

@VencentYoung
Last active December 15, 2015 21:29
Show Gist options
  • Save VencentYoung/5325769 to your computer and use it in GitHub Desktop.
Save VencentYoung/5325769 to your computer and use it in GitHub Desktop.
function [a,yy] = SinCosFit(x,y,n,xx)
% SinCosFit : Trigonometric function fitting and interpolating
% [a,yy] = SinCosFit(x,y,n,xx)
% use least-squares method to calculate the A B and C
% A B should be vectors, and the formula is like this
% y = C + Σ[A(i)*sin(i*x) + B(i)*cos(i*x)],i = 1,2...n
% n is given by the user
% input:
% x = independent variable
% y = dependent variable
% xx = value of independent variable at which the
% interpolation is calculated
% n = the order of trigonometric function
% output:
% yy = interpolated value of dependent variable
% Record of revisions
% Date Programmer Description of change
% ++++++++++++ +++++++++++++ +++++++++++++++++++++++
% 2011/10/08 Vencent.Young@XJTU Original code
if nargin<3
error('at least 3 input arguments required')
end
m = length(x);
if length(y)~=m;
error('x and y should be the same length')
end
z = ones(m,2*n+1);
a = zeros(2*n+1,1);
p = [1:1:n];
for i = 1:m
z(i,2:2:2*n) = sin(p*x(i));
z(i,3:2:2*n+1) = cos(p*x(i));
end
a = (z'*z)\(z'*y');
a = a';
l = length(xx);
for j = 1:l
yy(j) = a(1)+sum(a(2:2:2*n).*sin(p*xx(j)))+sum(a(3:2:2*n+1).*cos(p*xx(j)));
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment