Push button to halt a loop

  • Permalink
  • submit to reddit
  • Email
  • Follow


Hello.

Is there a way to code up a GUI that gracefully brings a program out of a loop (i.e to avoid using Ctrl + C)?
Something like:

a = 1;

while a ==1
....run and plot this...
'GUI code which sets a=0 when button is pressed' (thus ending the loop).
end

I'm trying to find a way to run a program indefinitely until a key/button is pressed.
0
Reply theguv81 (25) 5/30/2011 6:17:02 AM

See related articles to this posting

On May 30, 8:17=A0am, "Frank " <thegu...@hotmail.com> wrote:
> Hello.
>
> Is there a way to code up a GUI that gracefully brings a program out of a=
 loop (i.e to avoid using Ctrl + C)?
> Something like:
>
> a =3D 1;
>
> while a =3D=3D1
> ...run and plot this...
> 'GUI code which sets a=3D0 when button is pressed' (thus ending the loop)=
..
> end
>
> I'm trying to find a way to run a program indefinitely until a key/button=
 is pressed.

You don't really want to do that, but the way to achieve
this is to start the GUI component where the button appears
before you enter the loop, and then poll the state of the
button in each iteration of the loop.

Rune
0
Reply allnor (8506) 5/30/2011 6:22:58 AM

On 5/29/2011 11:17 PM, Frank wrote:
> Hello.
>
> Is there a way to code up a GUI that gracefully brings a program out of a loop
>(i.e to avoid using Ctrl + C)?
> Something like:
>
> a = 1;
>
> while a ==1
> ...run and plot this...
> 'GUI code which sets a=0 when button is pressed' (thus ending the loop).
> end
>
> I'm trying to find a way to run a program indefinitely until a key/button is pressed.

Yes, ofcourse, I do that all the time.  Very easy, like this:

have a STOP button. In its call back, read your userData struct
from figure (doc userData), which you'd already set up, and
set a flag in it to true, say STOP=true. Then save the userData
back.

The mainline (your loop), will, at the end of each iteration,
read userData and checks if the flag is true of false, if it
is true, it terminates the loop, and sets the flag to false
to be ready for the next time the mainline is called,
and then write userData back to figure. Something like

  moreWork = true;
  while moreWork

     .... busy work here
     .... if done, moreWork=false;

     %check if user hit STOP button
     userData = get(handles.figure1, 'UserData');
     if userData.state == STOP
        userData.state = RUN;  %reset for next time
        set(handles.figure1,'UserData',userData);
        moreWork = false; %to stop the loop
     end
end


Do not need to worry about race conditions between Stop button
callback and mainline, as main line will be interrupted untill
stop button callback is completed (matlab takes care of this).

Initially, in your GUI OpeningFcn (if you are using GUIDE), you'll
set up the userData struct and init this flag to false.

--Nasser

0
Reply Nasser 5/30/2011 6:38:47 AM

I thought maybe I should re-write this again to include  the
whole setup to make things more clear.

In OpeningFcn(), if using GUIDE, do
-------------------------------------------
   set(handles.figure1, 'UserData',[]);
   userData.stop = false;
   set(handles.figure1, 'UserData',userData);

In the STOP button callback, do  (this is the interrupt)
-----------------------------------
    userData = get(handles.figure1, 'UserData');
    userData.stop = true;
    set(handles.figure1,'UserData',userData);


In the mainline, (the RUN button callback) do
---------------------------------------------

     moreWork = true;
     while moreWork
  
        .... busy work here
        .... if done, moreWork=false;
  
         %check if user hit STOP button
         userData = get(handles.figure1, 'UserData');
         if userData.stop == true
            userData.stop = false;  %reset for next time
            set(handles.figure1,'UserData',userData);
            moreWork = false; %to stop the loop
         end
     end

  
--Nasser
0
Reply Nasser 5/30/2011 6:56:56 AM

Thanks Nasser for you're fast response. 
0
Reply theguv81 (25) 6/1/2011 1:21:02 AM

"Frank" wrote in message <is445u$qhn$1@newscl01ah.mathworks.com>...
> Thanks Nasser for you're fast response. 

Sorry, Nasser: 

I tried something like what you suggested. Actually I did it almost the same way before reading your post. With no success. To me this does not work.

The main loop always takes control until the simulation is done. The stop callback is queued and acts only after the main loop terminates. I am not able to find a workaround.

Am I missing anything?
0
Reply msiti (2) 1/17/2012 2:08:09 PM

On 1/17/2012 8:08 AM, Azimut wrote:
> "Frank" wrote in message<is445u$qhn$1@newscl01ah.mathworks.com>...
>> Thanks Nasser for you're fast response.
>
> Sorry, Nasser:
>
> I tried something like what you suggested. Actually I did it almost the same way
>before reading your post. With no success. To me this does not work.
>
> The main loop always takes control until the simulation is done. The stop callback
>is queued and acts only after the main loop terminates. I am not able to find a workaround.
>
> Am I missing anything?

humm.. I am sorry, I have no idea what are you refering to. I see
nothing in this message I can respond to.

--Nasser
0
Reply Nasser 1/17/2012 2:30:07 PM

The point is that the structure you suggested:

run_Callback
    userData = get(handles.figure1, 'UserData');
    if (userData.stop == true)
        userData.stop = false; %reset for next time
        set(handles.figure1,'UserData',userData);
        abort_simulation;
    end
simulation_loop;

stop_Callback %pushbutton
userData = get(handles.figure1, 'UserData');
userData.stop = true;
set(handles.figure1,'UserData',userData);

practically does not work, even though it should. Matlab apparently is not able to get the status update from "stop callback", perhaps because too busy with simulating the intensive "simulation_loop" called from "run_Callback".

However I found a trick to give Matlab time to check stop_Callback updates.
The code example above works if a statement like: pause(0.000001) is placed among run_Callback instructions.

(I found this trick in another thread, not my idea; at least in my case it works)
0
Reply msiti (2) 1/17/2012 3:07:09 PM

On 1/17/2012 9:07 AM, Azimut wrote:
> The point is that the structure you suggested:
>
> run_Callback
>      userData = get(handles.figure1, 'UserData');
>      if (userData.stop == true)
>          userData.stop = false; %reset for next time
>          set(handles.figure1,'UserData',userData);
>          abort_simulation;
>      end
> simulation_loop;
>
> stop_Callback %pushbutton
> userData = get(handles.figure1, 'UserData');
> userData.stop = true;
> set(handles.figure1,'UserData',userData);
>
> practically does not work, even though it should. Matlab apparently is
>not able to get the status update from "stop callback", perhaps because
>too busy with simulating the intensive "simulation_loop" called from "run_Callback".
>
> However I found a trick to give Matlab time to check stop_Callback updates.
> The code example above works if a statement like: pause(0.000001) is placed among run_Callback instructions.
>
> (I found this trick in another thread, not my idea; at least in my case it works)

First, I am glad things worked for you.

Second, I have no clue where the above code with 'abort_simulation' came
from, becuase I did not write that. Here is the link:

http://www.mathworks.com/matlabcentral/newsreader/view_thread/308463

Third, I gave you a pattern to follow, a general approach. I did not include
all the details and every thing. If you asked for more details, I would have
given you a link to an example code I did, here is one

Here is just one example showing how it works

http://12000.org/my_courses/UC_davis/spring_2011/MAE_121_eng_dynamics/lab/lab_one/index.htm

click on the HTML link there, and click on the source code. And yes, I did
use a pause for tiny amount to get this to run, I never said I did not as I was
just giving you a pattern, not an actual code with all the details. I did
not think I had to include every bit of everything each time I answer something.

But it is not important now. Since it works for you know.

--Nasser
0
Reply Nasser 1/17/2012 3:34:42 PM

Instead of "pause(0.0001)", use "drawnow;". "pause" command is extremely slow because it uses very inaccurate timing mechanism. If you're running a time-critical loop, NEVER use "pause" in your loop. Having said that, drawnow is not a perfect choice either. However, there is no delay. Only the overhead to process "drawnow" exists. So, if you're not running many GUI objects doing this and that, "drawnow" exits fairly well. In a very fast computer you may finish "drawnow" within 0.1ms, which is good for usual task.

Best,


"Azimut" wrote in message <jf42qt$8ni$1@newscl01ah.mathworks.com>...
> The point is that the structure you suggested:
> 
> run_Callback
>     userData = get(handles.figure1, 'UserData');
>     if (userData.stop == true)
>         userData.stop = false; %reset for next time
>         set(handles.figure1,'UserData',userData);
>         abort_simulation;
>     end
> simulation_loop;
> 
> stop_Callback %pushbutton
> userData = get(handles.figure1, 'UserData');
> userData.stop = true;
> set(handles.figure1,'UserData',userData);
> 
> practically does not work, even though it should. Matlab apparently is not able to get the status update from "stop callback", perhaps because too busy with simulating the intensive "simulation_loop" called from "run_Callback".
> 
> However I found a trick to give Matlab time to check stop_Callback updates.
> The code example above works if a statement like: pause(0.000001) is placed among run_Callback instructions.
> 
> (I found this trick in another thread, not my idea; at least in my case it works)
0
Reply sskimbox (22) 1/25/2012 10:26:10 PM

"Frank" wrote in message <irvcou$hv$1@newscl01ah.mathworks.com>...
> Hello.
> 
> Is there a way to code up a GUI that gracefully brings a program out of a loop (i.e to avoid using Ctrl + C)?
> Something like:
> 
> a = 1;
> 
> while a ==1
> ...run and plot this...
> 'GUI code which sets a=0 when button is pressed' (thus ending the loop).
> end
> 
> I'm trying to find a way to run a program indefinitely until a key/button is pressed.

function rotate_triangle()
axes('units','normalized',...
     'position',[0.1 0.1 0.8 0.8],...
     'color',[0.5 0.5 0.5],...
     'NextPlot','replacechildren',...
     'tag','plot_axes');
hp = plot([1 3 2 1],[2 4 1 2]);
set(hp,'tag','tplot');
xlim([-8 8]);
ylim([-8 8]);
% define rotation button
uicontrol('units','normalized',...
    'position', [0.42 .925 .15 .05],...
    'style','push',...
    'SelectionHighlight','off',...
    'string','rotate',...
    'fontweight','bold',...
    'fontsize', 10,...
    'fontname','arial',...
    'foregroundcolor',[0 0 0],...
    'callback',{@rotate_button},...
    'tag','rotate_button');

function rotate_button(hload,eventdata)
% locate and delete the main figure object
ax = findobj('tag','plot_axes');
hp = findobj('tag','tplot');
hb = findobj('tag','rotate_button');
stop_flag = get(hp,'userdata');
if ~isempty(stop_flag)
    if stop_flag == 0
        set(hp,'userdata',1)
        set(hb,'string','rotate');
    elseif stop_flag == 1
        set(hp,'userdata',0);
        set(hb,'string','stop');
    end
else
    set(hp,'userdata',0)
    set(hb,'string','stop');
end
t = hgtransform('Parent',ax);
set(hp,'Parent',t)
Rz = eye(4);
for r = 0:.1:2000*pi
    Rz = makehgtform('zrotate',r);
    set(t,'Matrix',Rz)
    drawnow
    pause(0.01)
    stop_flag = get(hp,'userdata');
    if stop_flag == 1
        break
    end
end
return
0
Reply nospam185 (247) 1/25/2012 11:27:09 PM

Thanks, Sung Soo.

drawnow is perfect for my purpose.
I think the picture is complete now.

best regards, A.



"Sung Soo Kim" <sskimbox@aol.com> wrote in message <jfpvi2$b50$1@newscl01ah.mathworks.com>...
> Instead of "pause(0.0001)", use "drawnow;". "pause" command is extremely slow because it uses very inaccurate timing mechanism. If you're running a time-critical loop, NEVER use "pause" in your loop. Having said that, drawnow is not a perfect choice either. However, there is no delay. Only the overhead to process "drawnow" exists. So, if you're not running many GUI objects doing this and that, "drawnow" exits fairly well. In a very fast computer you may finish "drawnow" within 0.1ms, which is good for usual task.
> 
> Best,
> 
> 
> "Azimut" wrote in message <jf42qt$8ni$1@newscl01ah.mathworks.com>...
> > The point is that the structure you suggested:
> > 
> > run_Callback
> >     userData = get(handles.figure1, 'UserData');
> >     if (userData.stop == true)
> >         userData.stop = false; %reset for next time
> >         set(handles.figure1,'UserData',userData);
> >         abort_simulation;
> >     end
> > simulation_loop;
> > 
> > stop_Callback %pushbutton
> > userData = get(handles.figure1, 'UserData');
> > userData.stop = true;
> > set(handles.figure1,'UserData',userData);
> > 
> > practically does not work, even though it should. Matlab apparently is not able to get the status update from "stop callback", perhaps because too busy with simulating the intensive "simulation_loop" called from "run_Callback".
> > 
> > However I found a trick to give Matlab time to check stop_Callback updates.
> > The code example above works if a statement like: pause(0.000001) is placed among run_Callback instructions.
> > 
> > (I found this trick in another thread, not my idea; at least in my case it works)
0
Reply mr_x0 (2) 1/26/2012 9:16:09 AM
comp.soft-sys.matlab 201232 articles. 513 followers. Post

11 Replies
204 Views

Similar Articles

[PageSpeed] 54

  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

Exit from a loop using push button
Dear all Please let me know how to exit from a loop using pushbutton in matlab gui? Thanks Praveen Praveen <praveenmn1@gmail.com> wrote in message <5a21b456-6b0d-4100-9795-34956947cae8@k5g2000pra.googlegroups.com>... > Dear all > > Please let me know how to exit from a loop using pushbutton in matlab > gui? > > Thanks > Praveen Something along these lines: % create a figure with a button figure ; ButtonHandle = uicontrol('style','push',... 'callback','set(gcbo,''userdata'',1,''string'','...

Push to Make (Single Pole) Button running a loop
Happy holidays all! I'm developing an application and, as a relative newbie to Python, have come across a stumbling block with Tkinter. I'd like to have a button that when pressed executes a loop (this could be a thread) and then stops execution when it's released (Push to Make - Single Pole in electronics terms). I've tried the regular way of associating the procedure with a callback and tried using <Button-1> and <ButtonRelease-1> bindings but am getting nowhere fast (in the latter case the button release event seems to occur anyhows). So my question is: ...

Event loop halts on mouse down over minimize, maximize and close buttons
When I mouse-down (left or right) on the minimize, maximize or close buttons my application stops processing events until mouse up. Once I mouse-up events are once again processed. Due to the nature of my program stopping event processing on mousedown is as good as an OS crash in that I have to restart the computer to get it back. Is this an MSW problem or a wxWidgets problem? Does anyone have any ideas how I can fix it or work around it? I have to be able to process events after a mouse-down before a mouse-up. On 29 Dec 2006 13:14:11 -0800 Micah <micahc@gmail.com> wrote: ...

Simulink
Hi all, May i have your advise how can i start my SIMULINK with a push button callback and stop the SIMULINK with another push button callback? Then before the Simulink is stopped by the 2nd push button, how can i export/send my SIMULINK result to a function that i have defined in workspace? Says that i have defined a function analyse.m for further process.. Many Thanks! "st " <cell_st@hotmail.com> wrote in message <ij5l0j$eco$1@fred.mathworks.com>... > Hi all, > > May i have your advise how can i start my SIMULINK with a push button callback and ...

How to know which push button have been pushed ?
Hi, I have created two pushbuttons who refer to the same callback. How can i do to know if it's the push button 1 that has been pushed or the other ? Thanks Nono "Nono" <decatoirearnaud@hotmail.com> wrote in message news:4938541.1115041274879.JavaMail.jakarta@nitrogen.mathforum.org... > Hi, I have created two pushbuttons who refer to the same callback. How can > i do to know if it's the push button 1 that has been pushed or the other ? > Thanks > Nono Take a look at GCBO and GCO. Also, it's pretty easy to send the button object's handle as an a...

Push button text changes when pushed down and up
How to get red button text if I click on it (where the value in the table will be -1) and remains red when pushed down, and remains black text in not pushed down, while browsing to the records? I have stored the value 0 and -1 in a column in the table. This is what I tried: Private Sub Toggle141_AfterUpdate() If Me.Toggle141.Value = 0 Then Me.Toggle141.ForeColor = 0 End If If Me.Toggle141.Value = -1 Then Me.Toggle141.ForeColor = 255 'red End If End Sub Private Sub Toggle141_Click() If Me.Toggle141.Value = 0 Then Me.Toggle141.ForeColor = 0 End If If Me.Tog...

how to connect a start button to a for loop and control the loop
hi everyone, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; I need a small help regarding the VI. VI has two "for loops" the VI should run in such a way that when the first loop ends I need to get a flash&nbsp; signal saying that the first loop had ended. Then i need a start button for the second loop so that I can start the loop when ever it is needed. I would be really thankful if any one can reply this thread thanks deepthi krishnamaneni Hi, &nbsp;&nbsp;&nbsp; This is not exactly the same but hope it serves your purpose. For Loops.vi: http://forums.ni.c...

multiple radio buttons with a depending push button
I have a Matlab GUI with 2 radio buttons and one push button depends on the selected radio button . I want to program these buttons , also When the Matlab GUI starts, one radio button is default selected. note < Iam not good in matlab gui so if anyone has aprogram similar to this or had any idea please write the codes for his idea > "mohamed elsayed" <mohamed_elsayed_1989@yahoo.com> wrote in message <iqvst2$nt7$1@newscl01ah.mathworks.com>... > I have a Matlab GUI with 2 radio buttons and one push button depends on the selected radio button . I want to progra...

How to select a button in a matrix of push button (Cocoa) ?
The radion button was created with Interface Builder. How to make a default (selected) button in this matrix ? abz@videotron.ca (Alain Birtz) wrote in message news:<abz-2807030845040001@192.168.1.3>... > The radion button was created with Interface Builder. > How to make a default (selected) button in this matrix ? If I am understanding you correctly, you just need to send the matrix a - (void)selectCellAtRow:(int)row column:(int)column message to select the radio button at a given row and column in a matrix. If you don't want to deal with rows & columns you...