How to terminate a simulation by pushbutton in other script

1 次查看(过去 30 天)
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.

回答(1 个)

Jan
Jan 2017-6-8
编辑:Jan 2017-6-8
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
  1 个评论
K VdB
K VdB 2017-6-8
Thanks for the answer!
I know that your solution will work. It is a method I would not like to use though.
I solved my problem by using the command 'drawnow' in the while loop.
Greetings
Kjartan

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Interactive Control and Callbacks 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by