Matlab argument validation either specific vector size or empty
조회 수: 46 (최근 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에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!