Break loop with button click Appdesigner GUI [Both plot and button are in different callback functions]
Show older comments
I have a GUI MATLAB
I have a button
and there is a loop like this
function RUN()
t=1:0.01:3600;
for i=1:numel(t)
y(1,i)=readValue();
plot(t(1:i),Tco(1:i));
pause(0.02)
end
end
function BUTTON_PRESS()
%BREAK FROM THAT LOOP
end
I want to break this loop when I click my button
Accepted Answer
More Answers (1)
Voss
on 23 Nov 2020
0 votes
You can define a variable that says whether the button has been clicked. Set the value of that variable in your button's callback function. Check the value of that variable on each iteration of your for loop, and if it says the button has been clicked, break out of the loop.
6 Comments
shubham kumar gupta
on 23 Nov 2020
Voss
on 23 Nov 2020
Your variable that says whether the button has been clicked (let's call it "is_button_clicked" for the sake of discussion) will need to be available to both functions. There are a number of ways to achieve this:
1) you can store is_button_clicked in the handles structure of your GUI (if you are using GUIDE, this structure is accessible via guidata())
2) you can make RUN() and BUTTON_PRESS() nested under another function that contains is_button_clicked
3) you can make is_button_clicked a global variable
shubham kumar gupta
on 23 Nov 2020
Edited: shubham kumar gupta
on 24 Nov 2020
Rik
on 24 Nov 2020
Do not use a global. It is much better to share data through guidata or by making them nested functions. You can even set the flag value as the UserData of a GUI element.
All other functions can access and overwrite global variable contents. Especially with such a short name as flag this risk is non-zero. If you really insist on using global variable, make the name as long as you can: include the function name and include a long description. You have 63 characters, use them.
global RUN_PLOT_GUI___flag_to_stop_plotting_loop_if_true
shubham kumar gupta
on 1 Dec 2020
Edited: shubham kumar gupta
on 1 Dec 2020
Rik
on 1 Dec 2020
Changing the name will not solve anything if your code is not working in the first place. It is a good habit.
Instead of holding down the shift button while typing on this forum (which is considered SHOUTING and impolite), did you try using breakpoints to debug your code?
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
