MATLAB: Store as array not variable

arrayfunctionleast squaresvariablevector

I have the following function:
function f = function42(params2,T0,theta_f)
% f = x^2 %f and x are dummy variables
global a b
nu = params2(1);
phi = params2(2);
wf2 = params2(3);
c1 = b^2*(((exp(a*2*pi)-cosh(a*b*T0))/sinh(a*b*T0))^2-1);
Fitted_Curve = c1*exp(-2*a*theta_f)+nu*((1+0.5*(4*a^2+1))*cos(theta_f+phi)-2*a*sin(theta_f+phi))+b^2-wf2
f = sum(abs(Fitted_Curve));
T0 and theta_f are 1×9 vectors Fitted_Curve comes out in the workspace as a 1×9 vecot also, however c1 does not, it comes out as a variable and therefore i dont think it is using the corresponding T0 with theta_f for each calculation. My question is how do i get c1 to be a vector so that the corresponding c1 is used with the corresponding theta_f in the equation Fitted_curve.
Side note.
anyone know if i am doing the least squares method correctly here in this function.

Best Answer

The classic trap!
c1 = b^2*(((exp(a*2*pi)-cosh(a*b*T0))/sinh(a*b*T0))^2-1);
The divide there will be interpreted as a matrix divide (ie solving a matrix equation). Sounds like you were wanting elementwise calculation, so change the / into a ./ Similarly, you will also need to change c1*exp(-2*a*theta_f) on the next line to c1.*exp(-2*a*theta_f)
As to the side note: try f = norm(Fitted_Curve) or f = Fitted_Curve*(Fitted_Curve') if you want least squares.
Also, finally: don't use global! Pass a and b in as parameters. If necessary, use anonymous function handles to "wrap" function42.
Related Question