2016-12-31 42 views
0

我有一個代碼可以爲彈簧擺彈簧創建正確的xy圖。當系統在時間上前進時,我想在xy圖上顯示彈性彈簧擺的動畫。如何才能做到這一點?如何在Matlab中繪製彈簧擺的彈簧擺的擺動運動

這裏是我的模擬代碼:

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'); 

這裏是我的功能代碼:

function dz = OdeFunHndlSpngPdlmSym(~, z) 
% Define Global Parameters 
global M K L g 


% Take output from SymDevFElSpringPdlm.m file for fy1 and fy2 and 
% substitute into z2 and z4 respectively 
%fy1=thetadd=z(2)= -(M*g*sin(z1)*(L + z3) + M*z2*z4*(2*L + 2*z3))/(M*(L + z3)^2) 
%fy2=deldd=z(4)=((M*(2*L + 2*z3)*z2^2)/2 - K*z3 + M*g*cos(z1))/M 

% return column vector [thetad; thetadd; deld; deldd] 
dz = [z(2); 
    -(M*g*sin(z(1))*(L + z(3)) + M*z(2)*z(4)*(2*L + 2*z(3)))/(M*(L + z(3))^2); 
    z(4); 
    ((M*(2*L + 2*z(3))*z(2)^2)/2 - K*z(3) + M*g*cos(z(1)))/M]; 
+0

謝謝我跑了添加的代碼,但圖形不斷放大到矢量結束點。我想保持xy圖的範圍仍然有擺,以便可視化鐘擺運動。 – PatStarks

回答

0

可以「模擬」動畫與連續更新FOR循環中的情節和assignig圖形對象變量。

喜歡的東西(I假定只使用的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 

每繪圖指令後「等等」指令。 這只是一個基本的動畫,當然。

+0

謝謝我運行添加的代碼,但圖形不斷放大到矢量的末尾。我想保持xy圖的範圍仍然有擺,以便可視化鐘擺運動。 – PatStarks

+0

@PatStarks我更新了答案。如果它再次不能工作(圖形不是靜止的),儘量不要在繪圖指令相關的每一行代碼之後使用「drawnow」並且使用「hold on」(每個組件的至少一條指令)。 – marcoresk