Manuel
Manuel

Reputation: 46

break loop if there is an input Matlab

I'm using fminsearch to find the optimal solution of a problem and for some reason that is not related to the issue, I'm doing it by parts, calling fminsearch repeatedly. So, I have access to the value of the function (fval) everytime I call it (the program prints fval). The thing is that sometimes I see how fval increases and diverges from the optimum and in that cases I want to make and input and tell the program to go to the next case (break).

I can't include and if that states if fval is increasing go to the next case, because sometimes it increase and ends converging to the optimal solution. And I can't put and input that ask if I want to continue in every iteration, the process would be to long and I would have to be in front of the computer all day

Ideas? Thanks

Upvotes: 1

Views: 88

Answers (1)

user2271770
user2271770

Reputation:

The idea is to use some GUI element (like push-buttons), because their action can interrupt asynchronously the currently running code.

To illustrate what I mean, here's some code that should be copied in a file named main_loop.m, then run:

%// Main function

function main_loop()

        %// Create pushbutton user interface
        h_btn = uicontrol(          ...
           'Style', 'pushbutton',   ...
           'String', 'Go Next',     ...
           'Parent', figure(),      ...
           'Callback', @cb_function ...
        );

        %// Create flag in button application data, with value
        %//   = false: continue looping;
        %//   = true:  break the current loop.
        setappdata(h_btn, 'flag', false);

        %// Loop simulation
        for k = 1:10
                for p = 1:10000
                        %// Simulation of calculation
                        pause(0.1);
                        disp([k,p]);

                        %// If button hit, reset flag and break
                        if getappdata(h_btn, 'flag')
                                setappdata(h_btn, 'flag', false);
                                break;
                        end;
                end;
        end;
end


%// Button callback

function  cb_function(h_btn, ~)

        %// Set flag to request a loop break
        setappdata(h_btn, 'flag', true);
end

Basically one creates a flag in the application data of a button: the action of the button will set the flag, while the main loop checks this flag to decide if continues or breaks. Please note that the flag is reset before breaking the inner loop.

Please read the comments in order to figure out where to insert your code; also, change the loops to your liking (e.g. while instead of for, multiply-nested loops etc.)

Upvotes: 2

Related Questions