Reputation: 552
I am trying to port some MATLAB code from GitHub to Octave and having problems with parsing the function input. There is/are optional input parameters which are handled thus:
% Optional parameter: maxLag
defaultMaxLag = 10 ;
checkMaxLag = @(x) validateattributes( x , { 'numeric' } , { 'positive' , 'numel' , 1 } ) ;
which are then handled by the inputParser
:
addOptional( parser , 'maxLag' , defaultMaxLag , checkMaxLag ) ;
If I try running this code as is I get the error
error: mdDelay: argument 'MAXLAG' is not a valid parameter
My Octave translation of this last code snippet is
addParamValue( parser , 'maxLag' , defaultMaxLag , checkMaxLag ) ;
which is also failing, but with the error message
error: if: undefined value used in conditional expression
error: called from
validate_arg at line 521 column 9
parse at line 470 column 11
The problem seems to be the anonymous function checkMaxLag
because when I run just this in the terminal I get
error: value on right hand side of assignment is undefined
so it seems that validateattributes
does not give a return value that the inputParser
requires. Any suggestions?
Upvotes: 0
Views: 704
Reputation: 13091
Your problem has nothing to with the change from addOptional
to addparamValue
to the port. The problem is simply that this fails (the error message recently on a newer version):
octave> validate_lag = @(x) validateattributes (x, {'numeric'}, {'positive', 'numel', 1});
octave> p = inputParser ();
octave> p.addOptional ('maxLag', 10, validate_lag);
octave> p.parse (20)
error: failed validation of MAXLAG
Validation function: @(x) validateattributes (x, {'numeric'}, {'positive', 'numel', 1})
You got caught by Octave's bug #49793. Basically, inputParser
expects a validation function that returns true or false. However, validateattributes
either returns nothing or fails. I recommend you do this:
function rv = validateattributes_with_return_value (varargin)
try
validateattributes (varargin{:});
rv = true;
catch
rv = false;
end_try_catch
endfunction
And then you can use
validate_lag = @(x) validateattributes_with_return_value (x, {'numeric'}, {'positive', 'numel', 1});
Upvotes: 3