MATLAB: LSQCURVEFIT Error When Trying To Optimize Parameters

array indices must be positivelsqcurvefitnonlinear least squares fit

I am trying to optimize 5 parameters using lsqcurvefite. I keep getting "Array indices must be positive integers or logical values". "Error in @(c,xdata) c(0)+c(1)…" line. I know my two vectors/data (VarName1 and VarName2 attached) are not positive integers, but that is my data for which I am trying obtain c0, c1, c2, c3, and c4 so that I can then fit my data with the best curve. How can I do nonlinear least squares fitting when most data will not be integers and not necessarily positive?
xdata = VarName1;
ydata = VarName2;
predicted = @(c,xdata) c(0) + c(1)*cos(xdata) + c(2)*cos(xdata) + c(3)*cos(xdata) + c(4)*cos(xdata);
c0 = [-276.8401; -0.01386; 0.007231; 0.011035; 0.001128];
[ahat,resnorm,residual,exitflag,output,lambda,jacobian] = ...
lsqcurvefit(predicted,c0,xdata,ydata);

Best Answer

Ok, here is the working code. Apparently, I needed to convert degrees to radians for this least squares computation on the cosines to work properly.
Angles = -180:20:180;
Angles = Angles';
Radians = (pi/180).*Angles;
theta = Radians(:,1);
y = VarName2(:,1);
plot(theta,y,'bo')
xdata = VarName1.*(pi/180);
ydata = VarName2;
lb = [-277; -100; -100; -100; -100];
ub = [-276.83; 100; 100; 100; 100];
predicted = @(c,xdata) c(1) + c(2)*cos(xdata) + c(3)*(cos(xdata)).^2 + c(4)*(cos(xdata)).^3 + c(5)*(cos(xdata)).^4;
c0 = [-276; -5; 5; 2; 1];
[c,resnorm,residual,exitflag,output] = ...
lsqcurvefit(predicted,c0,xdata,ydata,lb,ub);
hold on
plot(xdata,predicted(c,xdata),'r-','markersize',20)
hold off