Problem fitting with lsqcurvefit

10 views (last 30 days)
im getting the following error while executing the code "Index exceeds the number of array elements (2)", the goal is to fit a curve to points using a certain Formula:
[name,path]=uigetfile({'*.xlsx'});
Error using matlab.internal.lang.capability.Capability.require
Support for Java user interfaces is required, which is not available on this platform.

Error in uigetfile (line 117)
Capability.require(Capability.Swing);
filename = [path name];
opts = detectImportOptions(filename);
preview(filename,opts);
newtable = readtable(filename);
x = newtable{:,1};
y = newtable{:,2};
fun = @(w,x) sqrt(w(1)^2+w(2)^2*(x-w(3))^2)
x0 = [1 1];
w = lsqcurvefit(fun,x0,x,y)

Accepted Answer

Torsten
Torsten on 12 Sep 2022
M = [26 93
27 67.9
28 54.5
29 20.5
29.1 20.6
29.2 17.6
29.3 15.7
29.4 13
29.5 12
29.6 9.2
29.7 8.7
29.8 6
29.9 5.4
30 6.3
30.1 7.2
30.2 8.3
30.3 12.3
30.4 12.4
30.5 16.4
30.6 18.3
30.7 21.5
30.8 23.7
30.9 27.6
31 28.7
31.1 32.1
31.2 34.6
31.3 36.3
31.4 39.1
31.5 40.6
31.6 44.2
31.7 48.2
31.8 50.5
31.9 53.8
32 55.9
33 77.1];
x = M(:,1);
y = M(:,2);
fun = @(w) sqrt(w(1)^2+w(2)^2*(x-w(3)).^2);
fun2 = @(w)fun(w)-y;
w0 = [1 1 1];
w = lsqnonlin(fun2,w0)
Local minimum possible. lsqnonlin stopped because the final change in the sum of squares relative to its initial value is less than the value of the function tolerance.
w = 1×3
5.7432 24.9821 29.8623
hold on
plot(x,y,'o')
plot(x,fun(w))
hold off

More Answers (1)

Matt J
Matt J on 12 Sep 2022
Edited: Matt J on 12 Sep 2022
Your model has 3 unknowns w(1), w(2), and w(3). However, you are only providing initial guesses x0 for 2 of these variables.

Community Treasure Hunt

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

Start Hunting!