Break while loop app designer
42 ビュー (過去 30 日間)
古いコメントを表示
I need to break out of an infinite while loop using a toggle switch. That is, when the switch is set to on , the while loop will execute until the switch is set to off , please assist ,I have little experience with app designer . Thanks in advance.
0 件のコメント
回答 (1 件)
Benjamin Kraus
2022 年 1 月 7 日
Consider this example (you should be able to use this same pattern within App Designer with only a little tweaking):
function spinner
f = uifigure;
b = uibutton(f,'Text','Stop');
ax = uiaxes(f);
t = linspace(0,2*pi,100);
p = plot(ax,cos(t),sin(t),'Marker','.','MarkerSize',12,'MarkerIndices',1);
% For this example I'm using a "global" variable, but for your real app you
% will want to add a property to your app.
keepRunning = true;
% Move the button above the axes.
b.Position(2) = sum(ax.Position([2 4]));
b.ButtonPushedFcn = @(~,~) stopButtonPushed();
% Start the while loop
while keepRunning
p.MarkerIndices = mod(p.MarkerIndices,100)+1;
% It is essential you put either a drawnow or a pause in your while
% loop, otherwise your stopButtonPushed will never run.
drawnow
end
function stopButtonPushed()
keepRunning = false;
end
end
A more advance approach uses a timer instead of a while loop:
function spinner
f = uifigure;
s = uiswitch(f);
ax = uiaxes(f);
t = linspace(0,2*pi,100);
p = plot(ax,cos(t),sin(t),'Marker','.','MarkerSize',12,'MarkerIndices',1);
% Move the switch above the axes.
s.Position(2) = sum(ax.Position([2 4]));
% Use a timer to run your code instead of a while loop.
t = timer('Period',0.1,'ExecutionMode','fixedRate','TimerFcn',@(~,~) loop(p));
% Make sure your timer is deleted when the figure closes.
f.CloseRequestFcn = @(~,~) done(f, t);
% Use the switch to start and stop the timer.
s.ValueChangedFcn = @(~,~) switchToggled(s, t);
function switchToggled(s,t)
if s.Value == "On"
start(t);
else
stop(t);
end
end
function loop(p)
p.MarkerIndices = mod(p.MarkerIndices,100)+1;
drawnow
end
function done(f, t)
% You need to delete timers, or they will live until you close MATLAB.
stop(t);
delete(t);
delete(f);
end
end
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Develop Apps Using App Designer についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!