フィルターのクリア

Misunderstanding InputParser Validation Behavior

4 ビュー (過去 30 日間)
H.A. Camp
H.A. Camp 2018 年 5 月 25 日
コメント済み: H.A. Camp 2018 年 5 月 26 日
I seem to be confused as to the proper implementation of the inputParser when it comes to input validation. Consider the following function:
function out = testInputParser(varargin)
ip = inputParser;
ip.addParameter('x', [], @double);
ip.parse(varargin{:});
out = ip.Results.x;
end
These cases work as expected:
% Should pass:
>> testInputParser('x', 123)
ans =
123
% Should fail:
>> testInputParser('x', '123')
Error using testInputParser (line 5)
The value of 'x' is invalid. It must satisfy the function:
double.
...But then why do these cases NOT work?
% Expected to pass, but fails
testInputParser('x', -123)
Error using testInputParser (line 5)
The value of 'x' is invalid. It must satisfy the function:
double.
% Expected to fail, but passes
>> testInputParser('x', 'a')
ans =
a
I can avoid some of this heartburn by using @isnumeric for my input validator, but I also want to ensure I've got doubles and not, say, int16 values coming in.
So, this seems like strange behavior to me. What am I missing?

採用された回答

Walter Roberson
Walter Roberson 2018 年 5 月 25 日
@double is not an input validation function: it just takes the input and converts to double datatype. Whatever test is being done internally appears to accept positive results from the validation function.
You should be using a validation function such as @(x) isa(x, 'double') or @isfloat if single precision is also acceptable.
  1 件のコメント
H.A. Camp
H.A. Camp 2018 年 5 月 26 日
Ah, of course! Thanks, Walter, for your patience with such a simple problem. :) Somehow, I fooled myself into thinking that the act of type conversion would inherently perform the check when that's not really what it's intended for.
Much appreciated!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by