Search code examples
matlabmatlab-figureinterrupt

Matlab stop function's execution


I have an array. I am processing elements of this array in a for loop inside a function.

function results = processArray(array)
   for ii = 1:length(array)
      %some stuff here
      results(ii) = %getting the results for this particular element
   end
end

There might be a lot of elements and computations might take a lot of time. I want to be able to finish execution of the for loop at any arbitrary time when a user wants to do that so that the results for already processed elements would be available.

I was trying to make a figure with a button which would change a boolean flag. Inside the for loop I was checking the value of that boolean. If the boolean changed then the for loop should break.

function results = processArray(array)
   fig = figure;
   fig.UserData.continue = 1;
   uicontrol('Parent', fig', 'Style', 'pushbutton', 'String', 'stop', 'callback', @interrupt)

   for ii = 1:length(array)
      if(fig.UserData.continue == 0)
         break;
      end
      %some stuff here
      results(ii) = %getting the results for this particular element
   end
end

function interrupt(obj, ~)
   fig = obj.Parent;
   fig.UserData.continue = 0;
end

well, that does not work. The figure shows up only after all the computations are done already. If I draw the figure first using something like waitforbuttonpress and proceed to the for loop pressing the button does not stop the execution. I think the callback function is being executed only after the for loop is finished. Is there any way to solve this?


Solution

  • You will need to drawnow after you create the button, so it will show up. You also need to drawnow within the loop to update the button state. Then you should achieve what you want.

    drawnow force figure update, so it will slow down your computation a little.