How to combine argument validation with varargin

87 ビュー (過去 30 日間)
Matt J
Matt J 2023 年 12 月 21 日
コメント済み: Matt J 2023 年 12 月 22 日
How can I make varargin work in conjunction with an arguments block? In the function below, the first two inputs W and p have very specific validation criteria. However, I have additional arguments, which I am trying to capture with varargin, with no validation criteria that I would like to enforce at this point.
someFunc(5,1,'dog',{2},6)
function someFunc(W,p, varargin)
arguments
W {mustBeNumeric}
p int8 {mustBeScalarOrEmpty,mustbeInteger}=2
varargin
Function argument definition error in someFunc. varargin can only be used inside Repeating arguments block.
end
W,p, varargin
end
As shown, the call throws an error saying that varargin can only be used inside Repeating arguments blocks, but I can find no relevant documentation or examples on that. Removing varargin from the arguments block altogether also generates an error:
File: test.m Line: 5 Column: 24
Function argument definition error in someFunc. Arguments block and function line must contain the same arguments in the
same order, including ignored arguments.
Is there simply no way to use varargin and arguments in conjunction?

採用された回答

Paul
Paul 2023 年 12 月 22 日
My understanding from reading Avoid Using varargin for Repeating Arguments is that putting varargin into a Repeating arguments block without any restrictions would allow the code to work.
someFunc(5,1,'dog',{2},6)
W = 5
p = int8 1
varargin = 1×3 cell array
{'dog'} {1×1 cell} {[6]}
vargin elements are:
ans = 'dog'
ans = 1×1 cell array
{[2]}
ans = 6
function someFunc(W,p, varargin)
arguments
W {mustBeNumeric}
p int8 {mustBeScalarOrEmpty,mustBeInteger}=2
end
arguments (Repeating)
varargin
end
W,p, varargin
disp('vargin elements are:')
for ii = 1:numel(varargin)
varargin{ii}
end
end

その他の回答 (1 件)

Matt J
Matt J 2023 年 12 月 21 日
編集済み: Matt J 2023 年 12 月 21 日
This is one solution, but is very inconvenient, because it requires that I offload the argument checking to another function, checkIt(). Were I allowed to nest the checkIt function within someFunc, it wouldn't be so bad, but arguments blocks can't be used in nested functions (as of R2021b).
someFunc(5,1,'dog',{2},6)
W = 5
p = int8 1
varargin = 1×3 cell array
{'dog'} {1×1 cell} {[6]}
function someFunc(W,p, varargin)
[W,p] = checkIt(W,p);
W,p, varargin
end
function [W,p] = checkIt(W,p)
arguments
W {mustBeNumeric}
p int8 {mustBeScalarOrEmpty,mustBeInteger}=2
end
end

カテゴリ

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

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by