inputparser fails to accept correct value

7 ビュー (過去 30 日間)
xCuse
xCuse 2019 年 8 月 18 日
コメント済み: xCuse 2019 年 8 月 18 日
I'm currently trying to get the inputparser for my function to work. My code looks like this:
function [] = Test2 (BW,varargin)
defMethod = 2;
p = inputParser;
validImage = @(x) islogical(x);
addRequired(p,'BW',validImage);
addParameter(p,'method',defMethod,@(x) isinteger(x) && (x<3) && (x>0));
parse(p,BW,varargin{:});
Running this codes yields the following result:
Test2(BW,'method',1);
The value of 'method' is invalid. It must satisfy the function: @(x)isinteger(x)&&(x<3)&&(x>0).
Does anyone know what is causing this behaviour?
Ty for your help!
  2 件のコメント
Adam Danz
Adam Danz 2019 年 8 月 18 日
Test2() is a different function than Test(). Was it a typo?
xCuse
xCuse 2019 年 8 月 18 日
yes sorry it was a typo

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

採用された回答

Adam Danz
Adam Danz 2019 年 8 月 18 日
編集済み: Adam Danz 2019 年 8 月 18 日
isinteger(1) % = FALSE
This matlab function (which often causes confusion) does not determine if the input has an integer value. It determines if the intput is an interger-type (int8, int16, etc...). The input 1 is of class double, not integer-type.
If you need to determine if the input is an integer value,
@(x) mod(x,1)==0 && (x<3) && (x>0));
  3 件のコメント
Adam Danz
Adam Danz 2019 年 8 月 18 日
編集済み: Adam Danz 2019 年 8 月 18 日
Also, this
validImage = @(x) islogical(x);
addRequired(p,'BW',validImage);
can be simplified to this
addRequired(p,'BW',@islogical);
but if you want to accept true, false, 1, 0,
validImage = @(x) islogical(x) || (isnumeric(x) && ismember(x,[0,1]));
addRequired(p,'BW',validImage);
xCuse
xCuse 2019 年 8 月 18 日
Tyvm, every simplification is welcome! :)

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by