MATLAB: Error lsqcurvefit using Function value and YDATA sizes are not equal.

lsqcurvefit

ydata = [4.83 3.87 2.54 2.08 1.82 1.8 1.76 1.74];
xdata = [5 10 20 30 45 60 90 120];
fun2 = @(x,xdata)((42*exp((13/7)*x(1)*xdata))-140)/(10+(10* exp((13/7)*x(1)*xdata)));
x0 = [-1,1];
x = lsqcurvefit(fun2,x0,xdata,ydata)
I got the error message:
Error using lsqcurvefit (line 262)
Function value and YDATA sizes are not equal.
Error in dimethyl_kinetics2 (line 43)
x = lsqcurvefit(fun2,x0,xdata,ydata)
size(ydata)
size(fun2(x0,xdata))
ans =
1 8
ans =
1 1
I get that they need to be the same. But how do I do that?
Thanks a lot.

Best Answer

You need to do element-wise division:
fun2 = @(x,xdata)((42*exp((13/7)*x(1)*xdata))-140)./(10+(10* exp((13/7)*x(1)*xdata)));
With that change, your code works.