Can someone explain the flow of this script/function and the steps MATLAB goes through to get my output?

2 ビュー (過去 30 日間)
function dQdt = StateVar(t,Q)
global K1;
global K2;
global B1;
global B2;
global M1;
global M2;
x1 = Q(1);
x2 = Q(2);
v1 = Q(3);
v2 = Q(4);
dx1dt = v1;
dx2dt = v2;
dv1dt = (1/M1)*(-B1*v1 - (K1+K2)*x1 + K2*x2);
dv2dt = (1/M2)*(K2*x1 - B2*v2 - K2*x2);
dQdt = [dx1dt; dx2dt; dv1dt; dv2dt];
end
global K1;
global K2;
global B1;
global B2;
global M1;
global M2;
K1 = 1;
K2 = 1;
B1 = 1;
B2 = 1;
M1 = 1;
M2 = 1;
q0 = [1 0 -1 0];
time = [0 15];
[t,q] = ode45('StateVar', time, q0);
figure(1)
plot(t,q(:,2))
xlabel('Time (s)')
ylabel('x_2 (m)')
figure(2)
plot(t,q(:,3))
xlabel('Time (s)')
ylabel('v_1 (m/s)')
I've had to do a couple of problems for a class that involve code like this and I've been following a pattern to do it, but I don't understand what's happening. I especially don't understand the function part and how setting variables as Q(1)-Q(4) does anything or how dQdt affects the output. I'm having trouble articulating my question, but I'd really appreciate insight into how the program is using each variable to get me the output. Thanks for any help!
  1 件のコメント
Adam
Adam 2017 年 2 月 2 日
編集済み: Adam 2017 年 2 月 2 日
It is very difficult to explain the 'flow' of any code that parachutes in a bunch of global variables that may or may not exist and may contain absolutely anything.
The code after the end statement is not valid syntax unless it is in a different place than the function above it. If a file contains a function definition it can't have what amounts to a script tagged on after the end of the function.
I pity anyone who has to work with code as bad as this for a class!

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

回答 (1 件)

Star Strider
Star Strider 2017 年 2 月 2 日
That looks to be code from a much earlier version of MATLAB.
The ‘Statevar’ function is a nonlinear differential equation that the ode45 call then integrates. The plot calls plot the last two integrated variables, ‘dv1dt’ and ‘dv2dt’, respectively.

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by