cppiscute
cppiscute

Reputation: 747

Keep listening to the pushbutton from an external function{Different .m file}

This question is related to This

While running the while loop, how can I keep listening or looking at pushbutton2, so that if there is a push I can perform some extra operations ?

Upvotes: 0

Views: 83

Answers (1)

CitizenInsane
CitizenInsane

Reputation: 4875

Matlab is mono-threaded, that is when it is executing some code (i.e. your while loop) it cannot process any other events (i.e. your pushbutton) until code is finished.

Look at below simple example to demonstrate this:

%% --- GUI creation
function [] = mygui()
%[
    fig = figure(666);
    clf;
    uicontrol('Parent', fig, 'Units', 'Normalized', 'Position', [0.2 0.4 0.7 0.1], 'String', 'Start script', 'Callback', @onStartScript);
    uicontrol('Parent', fig, 'Units', 'Normalized', 'Position', [0.2 0.2 0.7 0.1], 'String', 'Say hello', 'Callback', @onSayHello);
%]
end

%% --- Event handlers
function [] = onStartScript(sender, args)
%[
    for i = 1:10,
        disp(i);
        pinv(rand(1200, 1200)); % Simulates long processing           
    end
%]
end
function [] = onSayHello(sender, args)
%[
    disp('Hello');
%]
end

It creates a simple figure with two push buttons (one to start the loop and one to simply display Hello text in the command window):

enter image description here

If you run this code by clicking Start script button and then clicking Say hello button, you will see that Hello text will only appear when the loop is completed:

>> mygui
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
 Hello
 Hello
 Hello
 Hello
 Hello

What is happening here is that matlab is locked executing your code while the operating system is still stacking message in it's message queue to indicate that the Say hello button was pressed. It is only when matlab returns to idle state that it can process these messages/events.

To force maltab to process it's message queue add a call to drawnow during the loop:

function [] = onStartScript(sender, args)
%[
    for i = 1:10,
        disp(i);
        pinv(rand(1200, 1200)); % Simulates long processing
        drawnow; % FORCE PROCESSING ANY PENDING GRAPHICAL EVENTS
    end
%]
end

You'll now see that GUI events are processed while the loop is executing:

>> mygui
     1
     2
 Hello
 Hello
     3
     4
     5
 Hello
     6
     7
 Hello
 Hello
     8
     9
    10

Upvotes: 2

Related Questions