Skipping Optional Positional Arguments

50 ビュー (過去 30 日間)
Stewart
Stewart 2024 年 10 月 25 日 22:36
回答済み: 埃博拉酱 2024 年 10 月 26 日 15:02
I am writing a routine that uses arguments to parse input parameters. After many years of using both inputParser and manual input parsing, I like using arguments. However, I seem to be running into some limitations.
I am trying to get arguments to ignore an optional positional arguments. Take the example function:
function y = foo(a,b,c)
arguments
a
b = 2
c = 3
end
y = a + b + c;
end
Suppose I want to specify arguments for a and c and use the default value of b. With manual parsing, I would just detect an empty value for b by calling foo(1,[],3). When using arguments, I can not achieve the same functionality by calling as foo(1,~,3) or similar syntax.
Is there a way to get this functionality without resorting to manual parsing?
  2 件のコメント
Stephen23
Stephen23 2024 年 10 月 25 日 23:27
"Is there a way to get this functionality without resorting to manual parsing?"
Not as far as I am aware. You should make an enhancement suggestion here:
Stewart
Stewart 2024 年 10 月 26 日 2:35
Just went ahead and created an enhacement suggestion. I wanted to check to see if I was missing a simple workaround, the timeline for getting this into a release definitely won't be quick.

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

回答 (3 件)

Star Strider
Star Strider 2024 年 10 月 25 日 23:36
I usually use varargin rather than arguments, however your calling syntax may not be appropriate
To illustrate —
out = foo(1,pi,3)
out = 7.1416
out = foo(1,[],3)
out = 6
out = foo(1,~,3)
Using ~ in this context is not supported.
function y = foo(a,varargin)
optargs = cell(1,2);
optargs(1:numel(varargin)) = varargin;
if isempty(optargs{1})
b = 2;
else
b = optargs{1};
end
if isempty(optargs{2})
c = 3;
else
c = optargs{2};
end
y = a + b + c;
end
Not everything is possible.
.

Walter Roberson
Walter Roberson 2024 年 10 月 26 日 3:53
Unfortunately you cannot use [] to trigger detection as "missing" for the purpose of default argument processing.
function y = foo(a,b,c)
arguments
a
b double {mustBeEmptyOrNumeric(b)} = 2
c = 3
end
if isempty(b); b = 2; end
y = a + b + c;
end
function mustBeEmptyOrNumeric(b)
if ~isempty(b) && ~isnumeric(b)
eidType = 'mustBeEmptyOrNumeric:notEmptyOrNumeric';
msgType = 'Input must be empty or numeric.';
error(eidType, msgType);
end
end

埃博拉酱
埃博拉酱 2024 年 10 月 26 日 15:02
It is recommended that you use name-value arguments:
function y = foo(a,options)
arguments
a
options.b = 2
options.c = 3
end
y = a + b + c;
end
Then you can specify c without b:
foo(1,c=3);

カテゴリ

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

製品


リリース

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by