MATLAB Optional Function Arguments

413 次查看(过去 30 天)
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
@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
Yes, I like that better. I added it to my enhancement request.

请先登录,再进行评论。

采纳的回答

Matt J
Matt J 2025-2-16
编辑:Matt J 2025-2-16
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
  3 个评论
Julian Leonard
Julian Leonard 2025-11-24,16:05
This should be explained in the documentation. Thank you for this solution.
This section here gives the impression, that optional arguments that can not be used independently from each other.
Walter Roberson
Walter Roberson 2025-11-24,20:32
You always have to pass something in a positional slot if you use a later positional slot.
You do not need to pass other name/value pairs if you wish to use particular name/value pairs.

请先登录,再进行评论。

更多回答(2 个)

Walter Roberson
Walter Roberson 2025-2-16
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
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
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
I'll look into how inputParser can be used in this context.
Thanks for your answer!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

产品


版本

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by