How to terminate a simulation by pushbutton in other script
3 views (last 30 days)
Show older comments
Hello everyone, let me sketch the situation first.
I've made a GUI which has some uicontrols. On of the pushbuttons starts the simulation.
The execution of the simulation is situated in another script (lets call it 'sim1')
.
main GUI:
function varargout = maingui(varargin) % standard function for GUI (not import for this thread)
...
function varargout = maingui_OutputFcn(hObject, eventdata, handles) % standard function for GUI (not import for this thread)
...
function startsimulation_Callback(hObject, eventdata, handles) % callback for the pushbutton
sim1(necessary variables) % this refers to another script 'sim1.m'
sim1:
while condition
... script...
end
I want to stop the simulation by clicking on another pushbutton on the main GUI. But I don't know exactly how. Clicking on a pushbutton ('stop simulation') doesn't generate a callback when Matlab is going through the while loop.
.
Thank you for your help.
0 Comments
Answers (1)
Jan
on 8 Jun 2017
Edited: Jan
on 8 Jun 2017
There is no way to stop sim1 magically from the outside. But you could provide the handles of a GUI object (the button or the figure itself) as input, if you convert sim1 into a function (which would have many further advantages compared to a script). Then you can check the status of the GUI object, if the simulation contains a loop:
function mainGUI
FigH = figure;
ButtonH = uicontrol('Style', 'ToggleButton', 'String', 'Stop', ...
'Callback', @StopButtonCB, 'UserData', 0);
pause(2);
StartSimulation(ButtonH);
end
function StopButtonCB(ButtonH, EventData)
set(ButtonH, 'UserData', 1, 'String', 'Wait');
end
function StartSimulation(ButtonH)
for k = 1:100
drawnow; % Give the GUI a chance to update the status
if get(ButtonH, 'UserData') == 1
fprintf('Stopped!\n');
break;
end
fprintf('%s please wait...\n', datestr(now, 0));
pause(1); % Your calculations...
end
end
See Also
Categories
Find more on Interactive Control and Callbacks 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!