MATLAB Optional Function Arguments

81 ビュー (過去 30 日間)
Ethan
Ethan 2025 年 2 月 16 日 20:35
コメント済み: Matt J 2025 年 2 月 18 日 17:58
I am reformatting some functions in my DTFTLab toolbox to use arguments blocks for argument validation.
I was previously using "nargin" and "isempty" statements to allow optional inputs and assign default values. I liked the fact that I could ignore an input by using "[]" and the function would assign it the specified default value.
Using the arguments block is more robust, but I'm unable to find a way to make multiple inputs independently optional.
For example:
function H_filter = bestLowPassFilter(signal, thresholdGain, omega, transition, method, cutoff)
arguments
signal (1,:) double
thresholdGain (1,1) double = 0.1
omega (1,:) double = linspace(-pi, pi, length(signal))
transition (1,1) double = pi/10
method char {mustBeMember(method,{'ideal','tukey','gaussian', 'raised-cosine'})} = 'ideal'
cutoff (1,1) double = NaN
end
%**Continues**
end
I would like every argument to be optional, but you cannot call this function while ignoring an input that precedes any used input.
bestLowPassFilter(X, 0.3, [], [], 'ideal');
If I call the function as shown above, I get an error because omega and transition must be scalar values.
The only workaround I've found is assigning NaN (like I have done with the "cutoff" argument) and then reassigning the true default with an isnan() statement, but that feels like the same as using nargin and isempty() statements.
Is there a way to bypass these inputs in the function call when the argument validation is done with arguments blocks?
Thanks for any advice!
  4 件のコメント
Ethan
Ethan 2025 年 2 月 18 日 17:04
@Matt J I think that will be a great feature, I would recommend having "~" denote a default-valued input.
Matt J
Matt J 2025 年 2 月 18 日 17:58
Yes, I like that better. I added it to my enhancement request.

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

採用された回答

Matt J
Matt J 2025 年 2 月 16 日 21:42
編集済み: Matt J 2025 年 2 月 16 日 22:02
Using the arguments block is more robust, but I'm unable to find a way to make multiple inputs independently optional.
The way you are meant to do that in the framework of arguments...end block processing is to convert those arguments to non-positional ones.
X=rand(1,10);
bestLowPassFilter(X, 0.3, method ='ideal')
Arguments processed
function bestLowPassFilter(signal, thresholdGain, options)
arguments
signal (1,:) double
thresholdGain (1,1) double = 0.1
options.omega (1,:) double = linspace(-pi, pi, length(signal))
options.transition (1,1) double = pi/10
options.method char {mustBeMember(options.method,{'ideal','tukey','gaussian', 'raised-cosine'})} = 'ideal'
options.cutoff (1,1) double = NaN
end
disp 'Arguments processed'
end
  1 件のコメント
Ethan
Ethan 2025 年 2 月 18 日 16:34
This is probably the best solution for my situation.
Transition and Cutoff would never be used together (cutoff is explicitly defined by the user or is calculated based on the transition and filter type).
Similarly, in the context of my DTFT toolbox - omega should always be a linspace vector from (-pi, pi) but I wanted to allow users the freedom to experiment with other spectrums (like filtering multiple 2pi-periodic copies).
Thanks for your answer!

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

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2025 年 2 月 16 日 21:40
Suppose you have a function call that you intend to be passing in thesholdGain, and skip omega and transition. So you call
bestLowPassFilter(signal, thresholdGain)
Now you would like to be able to skip unused parameters. Suppose you wanted to call
bestLowPassFilter(signal, transition)
Now, both thresholdGain and transition are scalars. How can argument processing possibly tell whether
bestLowPassFilter(signal, 0.2)
is an example of passing in thresholdGain or an example of passing in transition?
For that matter, how is it to be able to tell that the 0.2 is not an omega vector that happens to be only 1 element long?
The only possible way argument processing could potentially distinguish these variations is by using argname() and hoping that the passed parameter is not an expression and that the variable passed in happens to be distinguishable. For example you could match on whether the variable name happened to begin with 'o' or 'O', or happened to begin with 'tr' or 'TR' or 'Tr' or happened to begin with 't' or 'T' not followed by 'r' or 'R'. This is obviously not very robust.
The major alternative is to use name/value pairs.
  1 件のコメント
Ethan
Ethan 2025 年 2 月 18 日 16:44
I'm going to be changing the optional arguments to be name/value pairs, but I understand how omitting positional arguments would not make much sense. I was mostly wondering how I could replicate entering "empty" arguments with the "arguments...end block" how I had been passing "[]" as an argument when using nargin and isempty() statements for input validation.
Thanks for your answer!

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


Image Analyst
Image Analyst 2025 年 2 月 16 日 23:12
help inputParser
inputParser - Input parser for functions The inputParser object enables you to manage inputs to a function by creating an input parser scheme. Creation Syntax p = inputParser Properties CaseSensitive - Indicator to match case false (default) | true FunctionName - Name of function for error message empty character vector, ''. (default) | character vector | string scalar KeepUnmatched - Matching indicator false (default) | true PartialMatching - Partial matching indicator true (default) | false StructExpand - Structure indicator true (default) | false Parameters - Argument names cell array of character vectors Results - Results structure Unmatched - Unmatched input structure UsingDefaults - Inputs not passed explicitly to function cell array of character vectors Object Functions addRequired - Add required, positional argument into input parser scheme addOptional - Add optional, positional argument into input parser scheme addParameter - Add optional name-value pair argument into input parser scheme parse - Parse function inputs Examples web /MATLAB/help/matlab/ref/inputparser.html#mw_b0c59dd4-3fae-4b55-bbb8-59fc266bce5f openExample('matlab/ExtraParameterValueInputsExample') web /MATLAB/help/matlab/ref/inputparser.html#d126e885146 openExample('matlab/StructureArrayInputsExample') web /MATLAB/help/matlab/ref/inputparser.html#d126e885203 See also validateattributes, validatestring, varargin, arguments Introduced in MATLAB in R2007a Documentation for inputParser doc inputParser
  1 件のコメント
Ethan
Ethan 2025 年 2 月 18 日 16:38
I'll look into how inputParser can be used in this context.
Thanks for your answer!

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

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

製品


リリース

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by