Clear Filters
Clear Filters

Function value and YDATA sizes are not equal. Can anyone help?

1 view (last 30 days)
n=100;
xdata = linspace(0.3,10,n);
ydata = 1./(0.1*xdata) + 2 + 0.1*randn(n) ;
fun = @(x,xdata)1./(x(1).*xdata) + x(2);
x0 = [0.1 , 1];
x = lsqcurvefit(fun,x0,xdata,ydata)
times = linspace(xdata(1),xdata(end));
plot(xdata,ydata,'ko',times,fun(x,times),'b-')
legend('Data','Fitted exponential')
title('Data and Fitted Curve')

Answers (1)

Star Strider
Star Strider on 26 Nov 2021
The problem is the randn call. With one argument, it creates an (nxn) matrix, not a vector, so of course the sizes will not match. Adding another argument to create it as a (1xn) vector and it works —
n=100;
xdata = linspace(0.3,10,n);
ydata = 1./(0.1*xdata) + 2 + 0.1*randn(1,n) ;
fun = @(x,xdata)1./(x(1).*xdata) + x(2);
x0 = [0.1 , 1];
x = lsqcurvefit(fun,x0,xdata,ydata)
Local minimum found. Optimization completed because the size of the gradient is less than the value of the optimality tolerance.
x = 1×2
0.1001 1.9965
times = linspace(xdata(1),xdata(end));
plot(xdata,ydata,'ko',times,fun(x,times),'b-')
legend('Data','Fitted exponential')
title('Data and Fitted Curve')
.

Categories

Find more on Interpolation in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!