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

3 Ansichten (letzte 30 Tage)
Shashank Rajput
Shashank Rajput am 26 Nov. 2021
Beantwortet: Star Strider am 26 Nov. 2021
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')

Antworten (1)

Star Strider
Star Strider am 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')
.

Kategorien

Mehr zu Least Squares finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by