Break while loop app designer

32 vues (au cours des 30 derniers jours)
Keenan Jogiah
Keenan Jogiah le 6 Jan 2022
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.

Réponses (1)

Benjamin Kraus
Benjamin Kraus le 7 Jan 2022
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

Catégories

En savoir plus sur Develop Apps Using App Designer dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by