Set default value if no function input given

37 ビュー (過去 30 日間)
Anna Jacobsen
Anna Jacobsen 2021 年 2 月 7 日
コメント済み: Stephen23 2021 年 2 月 8 日
I want my function to use default values if no input variables are passed. I have done this in the past using the 'nargin' function. I prefer this approach to using the 'isempty' function. For some reason my code now returns an error when I only input 't' because the varargin{} arrays are technically empty. This error makes sense, but I don't understand how to get around it as I thought the if/else statements would take care of that. How can I debug this?
Error: Index exceeds the number of array elements (0).
function [V, varargout] = HH(t, varargin)
if nargin < 1
V0 = -60;
else
V0 = varargin{1};
end
if nargin < 2
I = 0;
else
I = varargin{2};
end

採用された回答

Stephen23
Stephen23 2021 年 2 月 7 日
編集済み: Stephen23 2021 年 2 月 7 日
You did not count the input t when using nargin. You can include the number of inputs before varargin in the logical comparisons:
if nargin < 2 % not 1 !!!!
V0 = -60;
else
V0 = varargin{1};
end
if nargin < 3 % not 2 !!!
I = 0;
else
I = varargin{2};
end
Or change the operator to <= (assuming exactly one input before varargin):
if nargin <= 1 % not <
V0 = -60;
else
V0 = varargin{1};
end
if nargin <= 2 % not <
I = 0;
else
I = varargin{2};
end
Another approach is to simply count the number of elements in varargin, which means that you can write code that is robust against future changes too, because you can change how many inputs there are before varargin.
if numel(varargin) < 1 % not NARGIN
V0 = -60;
else
V0 = varargin{1};
end
if numel(varargin) < 2 % not NARGIN
I = 0;
else
I = varargin{2};
end
  2 件のコメント
Anna Jacobsen
Anna Jacobsen 2021 年 2 月 7 日
The second approach worked! Thank you!
Stephen23
Stephen23 2021 年 2 月 8 日
@Anna Jacobsen: please accept my answer if it helped you!

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by