Matlab argument validation either specific vector size or empty
25 次查看(过去 30 天)
显示 更早的评论
I would like to restrict an input to a specific vector size of (1,3) but also allow an empty vector that can be dealt with later. Something like this:
function [outputArg] = sandboxfunction(inputArg1,opts)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
arguments
inputArg1 (1,3) double;
opts.inputArg2 (1,3) double = [];
end
inputArg2 = opts.inputArg2;
if isempty(inputArg2)
inputArg2 = someCalculation();
end
outputArg = inputArg1 + inputArg2;
end
Is this possible? I'm needing to handle a lack of inputs in a unique way that cannot be given a default value. Instead, I'm wanting to check if the input is empty and calculate its value.
UPDATE:
I just want to clarify that I also need to be able to handle an empty input, not just a lack of an input. So using:
opts.inputArg2 (1,3) double
and checking if inputArg2 is a field of opts will not be sufficient.
0 个评论
回答(2 个)
dpb
2023-8-8
So far, I've found the arguments block more trouble than simply handling the conditions explicitly for something relatively simple such as this...
function v=sandboxfunction(v1,v2)
if nargin<1, error('Missing Required Argument'), end
if nargin<2, v2=someCalculation(); end
assert(isvector(v1) & numel(v1)==3,'Arg 1 must be 3-vector')
assert(all(size(v2))==size(v1)),'Arg 2 must be 3-vector')
v=v1+v2;
end
Might be able to deal with the size restriction with the arguments block, but I've not used it enough to fully understand what it does in conjunction with other tests and it's not clear to me how to write your specific desire with its supplied functions (and I don't feel like experimenting with writing user-supplied one to work with it at the moment :) ).
2 个评论
dpb
2023-8-9
NOTA BENE the final version will also want check vector orientation or simply make both consistent in one direction or another...
Steven Lord
2023-8-9
There's no way with the ()-based size specification to say "the inputs must be EITHER this size OR this size" other than through the use of colon to say something like "This needs to be some row vector, but I don't care how many columns it has."
There is a validator function mustBeVector that accepts an option "allow-all-empties" to validate that the input must be either a vector or an empty, but in order to require that input to be a 1-by-3 if it is a vector it'll probably be easiest to write your own custom validator.
function mustBe1x3VectorOrEmpty(x)
if ~isempty(x) % empties don't error
assert(isequal(size(x), [1 3]), "Input must be either empty or a 1-by-3 vector")
end
end
1 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Argument Definitions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!