pause loop with "if" statement?
6 次查看(过去 30 天)
显示 更早的评论
Hello everyone
I'm using App Designer to do an animation with a while loop, I want the animation to pause when time reaches a value (let's say 5) I use an "if" statement to do that so I have the code below
The problem is that when I say: if (toc(t_h)-app.PauseTime) == 5 it does nothing (the animation doesn't stop)
but if I write: if (toc(t_h)-app.PauseTime) > 5 instead it does work but I don´t want it to stop in 5.01 or 4.99 I need it to stop in the exact 5
I any of you could give me a clue I would really appreciate that. Thanks!
properties (Access = public)
PauseTime = 0; % Description
PauseHandle = tic;
end
% Callbacks that handle component events
methods (Access = private)
% Button pushed function: StartButton
function StartButtonPushed(app, event)
close all
set(app.StartButton,'Text','Restart')
time = 60;
set(app.UIAxes, 'units','points')
cla(app.UIAxes);
cla(app.UIAxes2);
R = 65;
ang=linspace(0,2*pi,50);
xp=R*cos(ang);
yp=R*sin(ang);
% Animation
% Draw outter circle
patch(app.UIAxes,xp,yp,'w')
hold(app.UIAxes,'on');
hold(app.UIAxes2,'on');
axis(app.UIAxes, 'equal');
f = 0.016;
Nb=10;
% Balls
rho1 = 55;
n = linspace(0,360,Nb+1);
line = plot(app.UIAxes,NaN,NaN,'o', 'LineWidth', 1, 'MarkerSize', 15, 'color', 'k');
% Mark on 1st ball
mark = plot(app.UIAxes,NaN,NaN,'*', 'LineWidth', 1, 'MarkerSize', 5, 'color', 'r');
% Fixed Mark
plot(app.UIAxes,[55 65],[0 0], 'LineWidth', 5,'color','r');
% Sine Wave
% Static
Swx = linspace(0,time,time*100);
Swy = (pi/2)*sind(360*Swx*f);
plot(app.UIAxes2,Swx,Swy,'LineWidth', 1, 'MarkerSize', 1, 'color', 'k');
% Moving point Sine Wave
sw = plot(app.UIAxes2,NaN,NaN,'o', 'LineWidth', 1, 'MarkerSize', 5, 'color', 'r','MarkerFaceColor','r');
t_h=tic;
app.PauseTime=0;
while (toc(t_h)-app.PauseTime) < time
% Balls
t1=toc(t_h)-app.PauseTime;
f1 = f*360;
line.XData = rho1*cosd(n+f1*t1) ;
line.YData = rho1*sind(n+f1*t1) ;
app.Time.Value = t1;
% Point on sinewave
t2=toc(t_h)-app.PauseTime;
sw.XData = t2;
sw.YData = (pi/2)*sind(360*f*t2);
% Slider
t3=toc(t_h)-app.PauseTime;
app.Slider.Value = t3;
% Mark
t4=toc(t_h)-app.PauseTime;
f1 = f*360;
mark.XData = rho1*cosd(f1*t4);
mark.YData = rho1*sind(f1*t4);
if (toc(t_h)-app.PauseTime) == 5
PauseButtonPushed(app, matlab.ui.eventdata.ButtonPushedData)
end
drawnow
end
end
% Button pushed function: PauseButton
function PauseButtonPushed(app, event)
app.PauseHandle = tic;
uiwait(app.animation)
end
% Button pushed function: ResumeButton
function ResumeButtonPushed(app, event)
app.PauseTime = app.PauseTime + toc(app.PauseHandle);
uiresume(app.animation)
end
采纳的回答
cr
2021-9-1
You must give it a range of time period rather than a unique time point since the execution doesn't guarantee the particular line toc() will be executed at t = 5s. If you need it to stop only once try giving a shorter period.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!