parameter optimization in function

3 ビュー (過去 30 日間)
Elon Hendriksen
Elon Hendriksen 2022 年 7 月 22 日
回答済み: Rajiv Singh 2022 年 8 月 9 日
Hi!
I have written a code in which a nonlinear pendulum is modelled. Now with measured data from a pendulum I would like to optimize my damping coefficient so that the model in matlab fits the measured data. Since the damping coeficient is in a separate function file I do not know how to tackle this. See script in attachment.
In F_nonlin the damping coefficient is currently 0.000035 and fits the curve quite well but as mentioned above I would like matlab to optimize this value automattically.
Thanks in advance for the help!
Kind regards, Elon

回答 (2 件)

Alan Weiss
Alan Weiss 2022 年 7 月 22 日
Try putting the following code at the end of yours:
[dfinal,resnorm] = fminbnd(@(damping)trytofit(damping,x0,Acc_clean),0.00002,0.00005)
function delta = trytofit(damping,x0,Acc_clean)
tspan = Acc_clean(:,1)/1000-5.017;
[~, S] = ode45(@(t,y) F_nonlin(t,y,damping),tspan,x0);
delta = sum((S - Acc_clean(:,3)).^2,"all");
end
I changed the F_nonlin code as follows:
function dx = F_nonlin(~,x,Bfactor)
% Derivative function for a nonlinear pendulum model.
%
% States:
% x(1): theta
% x(2): d theta/dt
% system parameters:
g = 9.81; % gravitational constant (m/s^2)
m = 1.042; % mass pendulum
L = 0.210; % length pendulum
M = m*L;
K = m*g; %iets met g
B = Bfactor * 2 * sqrt(M*K); %0.000035 for fitted line
dx(1,1) = x(2);
dx(2,1) = -( K*sin(x(1)) + B*x(2)*abs(x(2)) ) / M;
I get the result dfinal = 3.1459e-05, pretty close to what you have.
My code searches for a minimum of the sum of squares of differences between the simulated pendulum and the data you have. The only thing it varies is the damping (Bfactor in F_nonlin, a scalar), so I use fminbnd to get the minimum.
Of course, it is possible I made an error somewhere, but I think that you see how I put the parameter Bfactor in the simulation to give something that a solver can vary to search for a minimum.
Alan Weiss
MATLAB mathematical toolbox documentation
  4 件のコメント
Alan Weiss
Alan Weiss 2022 年 7 月 22 日
I don't know what you mean. You had a null L variable that you were passing in; it didn't do anything because you redefined the L variable inside the code, so the passed value was ignored. Feel free to rearrange things if you like, but I gave you working, tested code.
Alan Weiss
MATLAB mathematical toolbox documentation
Torsten
Torsten 2022 年 7 月 22 日
In your code, L is an input variable to F_nonlin and you immediately overwrite that input by setting L to 0.21. One of these settings is superfluous.

サインインしてコメントする。


Rajiv Singh
Rajiv Singh 2022 年 8 月 9 日

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by