Exit function early and return output
367 次查看(过去 30 天)
显示 更早的评论
I have a rather long function with a single output. In a special case, the output can be calculated without executing the majority of the function. Currently I use an if-statement to bypass the remaining code in the special case, but it feels clumsy to have an if-statment around lots of code. In C++, one could avoid the if-statement with two return statements; however the return function in MATLAB exits the function without returning the output variable. Is there a similar trick in MATLAB to avoid nesting the majority of my function in an if-statement? I know I could use another function to execute the else-statement, but that seems just as awkward.
% CURRENT CODE
function out = myfunc(a,b,c)
% Some calculations
if a == 1 % Special case
out = foo;
else
% Lots of calculations
out = bar;
end
end
% "IDEAL" CODE WHICH DOESN'T WORK
function out = myfunc(a,b,c)
% Some calculations
if a == 1 % Special case
return foo
end
% Lots of calculations
return bar
end
0 个评论
采纳的回答
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!