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

조회 수: 1 (최근 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 CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by