William Napier
William Napier

Reputation: 27

MATLAB Restart function instead of return(cancel)

I've been looking over, but I don't think it exists. There is return to essentially force close your function, which is nice, but in my current script, I want if it does something incorrectly, to instead return to the start of the sub function that it exists in.

Are there any functions that exist already to do that, or will I have to make a system in order to let myself do that?

Upvotes: 0

Views: 3956

Answers (3)

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

Here is how I would do it if you are not looking for error handling, but just outcome handling

finishedSuccesfully = false
while ~finishedSuccesfully 
    output = myFunction();
    finishedSuccesfully = evaluateoutput(output);
end

Upvotes: 0

Naruil
Naruil

Reputation: 2310

Just use an while 1 loop to wrap around the whole function and continue when you want to restart the function.

Upvotes: 0

Dang Khoa
Dang Khoa

Reputation: 5823

Instead of using return, error out of the function when something is "done incorrectly", then use try/catch in a while-loop:

while 1
    try
        myFunction();
        break; % if myFunction() was successful, this will exit the while loop
    catch
        % do some sort of processing here, then go back to the while loop
    end
end 

The catch portion of the try/catch block will execute only if myFunction() had an error. return implies the function succeeded (whether or not it gave correct output is a different issue entirely).


Alternatively, you could put your function in a while-loop as suggested by @natan. Return some sort of error code, then check for that error code in the while condition.

Upvotes: 1

Related Questions