MATLAB: Bug in least squares fitting

least squares fit

I am trying to fit my data as follows and I get the error message below. Can anyone help? Thanks in advance. Cathy R
>> xdata = intvp(:,1)
xdata =
195
390
590
795
985
1195
1300
1410
1510
1600
1710
1885
2065
2270
2480
2695
2900
>> ydata = intvp(:,2)
ydata =
1.0139
0.9816
0.9606
0.8848
0.7149
0.4705
0.3130
0.2017
0.1224
0.0517
0.0210
0.0132
0.0041
0.0020
0.0172
-0.0020
0.0231
>> fun = @(x,xdata)x(1)*(1/(1 + (x(2)*exp(x(3)*xdata))))
fun =
@(x,xdata)x(1)*(1/(1+(x(2)*exp(x(3)*xdata))))
>> x0 = [1.0,0.01,0.0045]
x0 =
1.0000 0.0100 0.0045
>> x = lsqcurvefit(fun,x0,xdata,ydata) Error using lsqcurvefit (line 248) Function value and YDATA sizes are not equal.

Best Answer

The issue is that you are trying to do an element-wise division but are not using an element-wise operator. You can see that:
fun(x0,xdata)
returns a row vector, which is not the same size as ydata.
Change the definition of fun and use the element-wise division operator ./ as opposed to /
fun = @(x,xdata) x(1)*(1./(1 + (x(2)*exp(x(3)*xdata))))