Check for optional inputs in a function using exist

31 ビュー (過去 30 日間)
Haris K.
Haris K. 2020 年 10 月 28 日
回答済み: Walter Roberson 2020 年 10 月 28 日
Hi everyone. Is it wrong, prone to mistakes, or slower to check the existance of optional arguments in a function using exist()? For the purposes of the illustration, assume I have 2 required and 1 optional inputs named r1,r2 and op1, respectively.
function y = mafun(r1,r2,op1)
if ~(exist('op1', 'var')==1)
op1 = 'smthn';
end
%do smthn with r1,r2 and op1 (when needed)
end
  1 件のコメント
Walter Roberson
Walter Roberson 2020 年 10 月 28 日
if ~exist('op1', 'var')
op1 = 'smthn';
end
would be cleaner.

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

採用された回答

Walter Roberson
Walter Roberson 2020 年 10 月 28 日
I suspect that it is faster to check nargin.
Note: starting R2019b, it is possible to use an "arguments" block to do automatic default values.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by