MATLAB: Matrix dimensions must agree error for addition

fittingnlinfitnonlinear

I am trying to fit the following six parameter function
equation=@(b,x) 0.5*b(1)*(1+((b(2)-x-(b(3)/5.0))/(((b(2)+x+(b(3)/5.0)).^2-(4*x*b(2))).^0.5)))+0.5*(1/(1+exp(-(x-b(5))/0.1)))*b(4)*(1+((b(5)-x-(b(6)/5.0))/(((b(5)+x+(b(6)/5.0)).^2-(4*x*b(5))).^0.5)))+2;
With nlinfit, using two vectors (xvalues, yvalues) of equal length as input values and some initial parameter guesses.
[coeffs]=nlinfit(xvalues,yvalues,equation,[22,0.5,0.001,145,1.05,0.001]);
However, matlab gives the following error:
Error using nlinfit (line 205)
Error evaluating model function
'@(b,x)0.5*b(1)*(1+((b(2)-x-(b(3)/5.0))/(((b(2)+x+(b(3)/5.0)).^2-(4*x*b(2))).^0.5)))+0.5*(1/(1+exp(-(x-b(5))/0.1)))*b(4)*(1+((b(5)-x-(b(6)/5.0))/(((b(5)+x+(b(6)/5.0)).^2-(4*x*b(5))).^0.5)))+2'.
Error in ITC_fit (line 13)
[coeffs]=nlinfit(xvalue,yvalue,ITC_equation,[22,0.5,0.001,145,1.05,0.001]);
Caused by:
Error using +
Matrix dimensions must agree.
It seems as if somewhere in the equation a parameter b(i) is interpreted not as a point variable, but a matrix, but I cannot identify where.
Many Thanks,
Theo

Best Answer

When in doubt, vectorize every multiplication, division, and exponentiation that does not specifically involve a scalar. I used the vectorize function to vectorize all of them here:
equation=@(b,x) 0.5.*b(1).*(1+((b(2)-x-(b(3)./5.0))./(((b(2)+x+(b(3)./5.0)).^2-(4.*x.*b(2))).^0.5)))+0.5.*(1./(1+exp(-(x-b(5))./0.1))).*b(4).*(1+((b(5)-x-(b(6)./5.0))./(((b(5)+x+(b(6)./5.0)).^2-(4.*x.*b(5))).^0.5)))+2;
See if that solves your problem.