In a function with multiple outputs, if one output is empty does that output still need to be calculated within the function?

Say I have a function [a,b] = functionname(c), that looks something like this:
[a,b] = functionname(c)
List of steps to calculate a
List of steps to calculate b (which require a has previously been calculated).
Is there a way to ONLY calculate a? I'm aware that I can type [a,~] = functionname(c), but this will still carry out the list of steps to calculate b (which take a while). I'm looking for something like this:
[a,b] = functionname(c)
List of steps to calculate a
if b is not ~
List of steps to calculate b
end
However I just can't work out the criteria I'm looking for in the if statement.
I'm aware I could separate this into two functions, and this is the way I'll go about it if what I'm after isn't possible, but I'd like to stick to the one function if possible.
Thanks!

 採用された回答

dpb
dpb 2015 年 12 月 12 日
編集済み: dpb 2015 年 12 月 13 日
[a,b] = functionname(c)
List of steps to calculate a
if nargout > 1
List of steps to calculate b
end
doc nargout % and friends and Function descriptive section for details...
Alternatively,
[a,b] = functionname(c)
List of steps to calculate a
if nargout==1, return, end % bail if don't need to compute b
List of steps to calculate b
NB: nargout also returns 2 for syntax [~,b] = functionname(c); even though there's only one return argument saved; the numbering is length of the list, not actual outputs assigned so above logic is still valid. (Of course, if there were three possible outputs and the call were [~,~,c] = functionname(c); you'd not be able to know that the effort to compute b is futile unless it's as above and c is also dependent upon b.)

1 件のコメント

Luke
Luke 2015 年 12 月 13 日
編集済み: Luke 2015 年 12 月 13 日
Fantastic, nargout does the trick nicely for what I'm after! Like you say, it would be a problem if I was after [~,b] and didn't want to compute a, but in my code I need to calculate a in order to calculate b, so nargout is perfectly fine! Thank you very much!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeArgument Definitions についてさらに検索

質問済み:

2015 年 12 月 12 日

編集済み:

2015 年 12 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by