如何在Matlab中绘制带弹簧的弹性摆的摆动

时间:2016-12-31 17:43:57

标签: matlab animation plot

我有一个代码可以为带有弹簧的弹性摆创建正确的xy图。我想在xy图上展示弹性摆锤的动画,因为系统在时间上前进。怎么办呢?

这是我的模拟代码:

include ':app', ':OfflineMapp', ':findhike', ':sharelocation', ':weather'

这是我的功能代码:

clc
clear all;

%Define parameters

global M K L g;
M = 1;
K = 25.6;
L = 1;
g = 9.8;


% define initial values for theta, thetad, del, deld
theta_0 = 0;
thetad_0 = .5;
del_0 = 1;
deld_0 = 0;
initialValues = [theta_0, thetad_0, del_0, deld_0];

% Set a timespan
t_initial = 0;
t_final = 36;
dt = .1;
N = (t_final - t_initial)/dt;
timeSpan = linspace(t_final, t_initial, N);

% Run ode45 to get z (theta, thetad, del, deld)
[t, z] = ode45(@OdeFunHndlSpngPdlmSym, timeSpan, initialValues);

% initialize empty column vectors for theta, thetad, del, deld
M_loop = zeros(N, 1);
L_loop = zeros(N, 1);
theta = zeros(N, 1);
thetad = zeros(N, 1);
del = zeros(N, 1);
deld = zeros(N, 1);
T = zeros(N, 1);
x = zeros(N, 1);
y = zeros(N, 1);

% Assign values for variables (theta, thetad, del, deld)
for i = 1:N
    M_loop(i) = M;
    L_loop(i) = L;
    theta(i) = z(i, 1);
    thetad(i) = z(i, 2);
    del(i) = z(i, 3);
    deld(i) = z(i, 4);
    T(i) = (M*(thetad(i)^2*(L + del(i))^2 + deld(i)^2))/2;
    V(i) = (K*del(i)^2)/2 + M*g*(L - cos(theta(i))*(L + del(i)));
    E(i) = T(i) + V(i);
    x(i) = (L + del(i))*sin(theta(i));
    y(i) = -(L + del(i))*cos(theta(i));
end

figure(1)
plot(x, y,'r');
title('XY Plot');
xlabel('x position');
ylabel('y position');

1 个答案:

答案 0 :(得分:0)

您可以在连续更新FOR循环和将图形对象赋值给变量的情节中“模拟”动画。

类似的东西(我假设只使用x,y作为时间数组t的数组函数)

%In order to block the axis and preventing continuous zoom, choose proper axes limit
x_lim = 100; %these values depends on you, these are examples 
y_lim = 100;
axis equal
axis([-x_lim x_lim -y_lim y_lim]); %now x and y axes are fixed from -100 to 100
ax = gca;


for i=1:length(t)
 if i > 1
  delete(P);
  delete(L);
 end

 P = plot(x(i),y(i)); %draw the point
 hold on
 L = quiver(0,0,x(i),y(i)); %draw a vector from 0,0 to the point
 hold on
 %other drawings
 drawnow
 pause(0.1) %pause in seconds needed to simulate animaton. 
end
每次绘图指令后

“保持”指令。 当然,这只是一个基本的动画。