Animating plot in a for loop

I have the following figure and i want to animate it with addpoints but couldn't work it out.
dy is the displacement from an ode solver, which is a matrix of 549x4 doubles and n = 2, so i only plot the dy(:,3) and dy(:,4)

2 个评论

I don't know. MATLAB cannot convert your image into code. Attach your code so we can run it. What is "addpoints" - is that a built-in or custom function? Attach dy in a .mat file. Make it easy to help you not hard.
Sorry. Here are the codes. You can run the code Vibration_Plot.m and enter the forces as '0' (they should be in quotes). The MDK.m is only for generating the matrices.

请先登录,再进行评论。

 采纳的回答

Cris LaPierre
Cris LaPierre 2021-1-16

0 个投票

Use the animatedline function. Follow this example from the documentation.

6 个评论

I have tried it but i get the error 'values must be handle'
Please show us the code you've written that uses the animatedline function so we can try to determine what's causing that error.
%Initial conditions
% q0=[5 -1]; %Initial displacement
q0 = [1 1];
v0=[0 0]; %Initial velocities
ti = 0; %Initial time
tf = 30; %Final time
%% ODE solver
tspan = [ti tf];
init = [v0,q0];
[t,dy]=ode45('ydot',tspan,init)
L=animatedline;
for i = 1:n
addpoints(L,t,dy(:,i+n));
subplot(n,1,i)
title(['Response q',num2str(i)]);
xlabel('Time, seconds'); ylabel('Displacement, m');
grid on;
drawnow;
end
function ydot=ydot(y)
ydot(1)=(-((12)*y(3)+(-2)*y(4)+(0)))/(1);
ydot(2)=(-((-2)*y(3)+(12)*y(4)+(0)))/(4);
ydot(3)=y(1);
ydot(4)=y(2);
ydot = ydot(:);
end
First, get your ode working correctly. See this example. I would avoid giving your function and output variable the same name. You might be creating some sort of recursive function that way.
[t,dy]=ode45(@ydotI,tspan,init)
function ydot=ydotI(t,y)
ydot(1)=(-((12)*y(3)+(-2)*y(4)+(0)))/(1);
ydot(2)=(-((-2)*y(3)+(12)*y(4)+(0)))/(4);
ydot(3)=y(1);
ydot(4)=y(2);
ydot = ydot(:);
end
It's easier to debug one thing at a time. Once you have the ode working, then focus on the animation. It's usually a good idea to only include in the for loop code that needs to be run multiple times. The title, labels, and grid commands can be set once, so move those before the loop.
It is my suspicion you will have to create an animated line for each subplot.
Here is a simplified working example that you can modify to your needs.
L=animatedline;
axis([ti,tf,-4,4])
title(['Response q',num2str(i)]);
xlabel('Time, seconds'); ylabel('Displacement, m');
grid on;
for i = 1:length(dy)
addpoints(L,t(i),dy(i,1));
drawnow
end
Thank you so much! I will work on this.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Animation 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by