## How to find the best fit sine wave to some data clear all tic; global x1; global y; ## First lets make some data. ## One example of where you might get data like this: ## If you look at Jupiter's moon's and plot their position over ## several days you can get data that is part of one sine wave. x1=0:7; f=.05 y=1.7*sin(2*pi*f*x1+.3); plot(x1,y) ## now define a function that has one output ## that should be minimized. function fs=frs(x3) global y; global x1; a=x3(1); # magnitude of the sine wave f=x3(2); # frequency th=x3(3); # phase shift ## Now calculate a guess wave yy=a.*sin(2*pi*f*x1+th); ## find the sum of the magnitude of the errors fs=sum(sum(abs(yy-y))); endfunction ## q is the starting guess ## [ magnitude, frequency, phase shift ] q=[1,.0001,.006] ## next there are 2 solvers shown -- just try either one of them #p=fminunc(@frs,q ) p=sqp(q,@frs) # The answer come back in p ## now plot the results against the original. t=0:.01:7; yt=p(1).*sin(2*pi*p(2).*t+p(3)); hold on plot(t,yt,'r') # the result of the curve fitting is the red line hold off toc