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

 채택된 답변

Walter Roberson
Walter Roberson 2020년 4월 24일

1 개 추천

Assign the desired value to the output variable. Then use return

댓글 수: 1

Toder
Toder 2020년 4월 24일
Thanks, Walter. Much more elegant than a huge else statement!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

릴리스

R2019b

질문:

2020년 4월 23일

댓글:

2020년 4월 24일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by