5 views (last 30 days)

Hello to everyone! I'm tryng to solve this data fitting problem with the following code, but as you see from the plot it seems doesn't fit well the points, what problem could be?

s = linspace(245,210,40); % spring lenght

q =linspace(310*pi/180,340*pi/180,40); % swingarm angle

fun = @(x,s)(2*pi - (acos((x(8)^2+x(10)^2-sqrt(x(5)^2+x(6)^2-2*x(6)*x(5).*cos(acos((x(1)^2+x(2)^2-s.^2)/(2*x(1)*x(2)))+x(3)+x(4))).^2)/(2*x(8)*x(10))) - x(9) - x(7)) - x(7))*180/pi;

x0 = [117,222,31.4*pi/180,7.3*pi/180,45,210,30*pi/180,90,75*pi/180,185]; % initial guess

lb = [105,215,27*pi/180,5*pi/180,35,200,22*pi/180,75,65*pi/180,175] % Lower bound

ub = [125,235,37*pi/180,10*pi/180,55,225,37*pi/180,100,80*pi/180,195] % Upper bound

x = lsqcurvefit(fun,x0,s,q,lb,ub)

plot(s,q*180/pi,'ko') % data to fit

hold on

plot(s,fun(x,s),'b-') % optimized parameters

legend('data to fit','optimized parameters')

ylabel('swingarm angle (q)')

xlabel('spring lenght (s)')

This is the plot:

Matt J
on 29 Nov 2020

Edited: Matt J
on 29 Nov 2020

John D'Errico
on 29 Nov 2020

Edited: John D'Errico
on 29 Nov 2020

Honestly, I would NOT solve it like that. Not even remotely so. Using lsqcurvefit for this just seems fraught with problems.

What might I do? I would look at the model, in the form of a Taylor series expansion, for the expansion of this function of s. (I'd also learn to use radians. Degrees are a bad thing, and what you have here is a frustrating amalgam of the two. It makes your code far more complicated than it need be.) Expand it around the midpoint of the interval of interest, thus around s at an extension of 225.

So your model wants to be in the form of a known extension at s = 225, plus a linear term, with a known slope.

Now I would look to find parameters that produce the desired linear behavior, while minimizing the higher order terms in that series expansion.

You know the relationship between s and q that you wish to find. It is just a straight line between the two end points. So now, look for parameters that kill off the higher order terms in the Taylor expansion, but maintain the desired low order terms as you need them.

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

Start Hunting!
## 2 Comments

## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/667768-lsqcurvefit-bad-fitting-results#comment_1168923

⋮## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/667768-lsqcurvefit-bad-fitting-results#comment_1168923

## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/667768-lsqcurvefit-bad-fitting-results#comment_1169493

⋮## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/667768-lsqcurvefit-bad-fitting-results#comment_1169493

Sign in to comment.