I am working on translating code from MatLab into R, however I am completely new to MatLab. I am having trouble understanding how what is happening in the MatLab code and how I can translate this to R. Here is the issue:
In the code a function calls another function called @fit_sine
x0=[max(y),2*3.14159/360,0.01,mean(y)];
options = optimset('Display','off');
coeff=lsqcurvefit(@fit_sine,x0,x,y,[],[],options);
fit=coeff(1).*sind(coeff(2).*x+coeff(3))+coeff(4);
This is the function @fit_sine:
function F=fit_sine(x,xdata)
F=x(1).*sind(x(2).*xdata+x(3))+x(4);
However nowhere is xdata defined. This is the step that is confusing to me. In R there is a similar function to lsqcurvefit which is nls but I have been unable to reproduce similar results as this MatLab code.
Here is the data used for x and y:y = -0.4764 -1.0880 -1.0115 -0.8586 -0.7822 -0.7058 -0.4000 0.3644 0.8231 0.7466 0.5173 0.4408
x = 0 30 60 90 120 150 180 210 240 270 300 330
As well as the output of coeff:coeff = 0.9098 0.8974 -157.6722 -0.1853
EDIT:
Solution:
func <- function(x0, x) (x0[1]*sin((x0[2]*x+x0[3])*(pi/180))+x0[4])
library(pracma)
coeff <- lsqcurvefit(func, x0, x, y)
fit=coeff$x[1]*sin(coeff$x[2]*x+coeff$x[3]*(pi/180))+coeff$x[4]