MATLAB: Is there a way to abort the code inside a function

aborting the programMATLAB

Hey there,
Happy to know people are there when there is a challenge. I see that return function is used to abort the code when it appears in the root level of an m-code. But when used in a function, it returns the program flow back to the invoking function.
Having this in mind, I wanna terminate the whole program when a sign of accomplishment is met inside a function. One way seems to be using return for several times to reach the root level. but what's so frustrating here is that this method implies checking the condition in each return again and again till getting into the root.
I know that error function would resolve the issue, but it's not sensible to produce an error when the code is successfully accomplished.
Please advise as necessary.

Best Answer

The proper way to do this is indeed to use return and propagate the return value back to the main function.
You can, however, abuse error to do what you want. Throw an error with your own id and catch it in your main:
function out = main(a, b, c)
try
%...

%code that will end up in subfunction
catch exception
if strcmp(exception.msgID, 'poyua:completed')
return;
else
rethrow(exception);
end
end
end
function out = subfunction(d, e)
while true
%...
if completed
error('pouya:completed', '');
end
end
end