Animating a ball in Matlab

半城伤御伤魂 提交于 2019-12-04 06:25:16

问题


I have a ball with these two equations: x(t) = v0*cos(α)*t and y(t) = h + v0*sin(α)*t− 1/2 gt^2 , where t ∈ [0,t final] is the time variable, h is the height, v0 is the initial speed, α is the angle made by v0 with the horizontal, g = 9.8 m/s^2. The floor is at y(x) = 0.

I need to draw a small animation of the ball moving on the plot. I now I should use for, plot, drawnow, but I don't know how to do it.

Can you tell me how to obain this animation?


回答1:


First, here are some test variables to start with, including the acceleration due to gravity:

g = 9.8; %// m/s^2
v0 = 2; %// m/s
alpha = pi/6; %// Radians
h = 30; %// Start at 30 metres
t_final = 4.5; %// Seconds
t_vector = 0 : 0.01 : t_final;

t_vector in the last line of code creates a vector of points from the initial time of t = 0 up until our ending time in steps of 0.01. With these defined, our job is to go through each of these points in our vector and plot our ball. Next, let's create anonymous functions for each x and y to make our plotting easier:

x = @(t) v0*cos(alpha)*t;
y = @(t) h + v0*sin(alpha)*t - 0.5*g*t.^2;

What you can do next is use a for loop and go through each value of t_vector up until t_final and plot the individual point. You should probably make the point big so we can actually see what the ball looks like:

close all;
figure; hold on;
for t = t_vector
    plot(x(t), y(t), 'b.', 'MarkerSize', 16);
    axis([0 t_final 0 h]);
    pause(0.01);
end

The above code will first close any figures we have open, spawn a new figure and use hold on so that we can call plot multiple times and append points to the graph without it erasing each time. Then, for each point in time, we plot the location on the graph as a blue dot, then make the size of the dot 16. We also make sure that the axis doesn't automatically adjust itself by enforcing that the x values are restricted between t = 0 up to t = t_final. We also restrict the y values from y = 0 up to the initial starting height, which is 30 in my example. At each point, we pause by 0.01 ms so you can see the drawing of the points.

As a bonus, this is what the figure looks like as an animated gif:



来源:https://stackoverflow.com/questions/27747409/animating-a-ball-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!