How to set mutually exclusive arguments in matlab?

10 ビュー (過去 30 日間)
cui,xingxing
cui,xingxing 2020 年 11 月 16 日
コメント済み: cui,xingxing 2020 年 11 月 17 日
How to use the new "arguments" parameter qualifier to control mutually exclusive two(or more) parameters as function inputs?
for example:
function out = twoStats(x,y)
arguments
% If you have input x, you cannot input y
% If you have input y, you cannot input x
end
end
similar question:
  1 件のコメント
Jon
Jon 2020 年 11 月 16 日
I have been looking through the documentation. It appears that the input validation only operates on a single argument at a time. I don't see any mechnisim for making the validation of one input dependent upon another, e.g. must be empty if b is not empty. Obviously you could check this yourself, but I understand that you want to use the new argument feature to do this

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

採用された回答

Bruno Luong
Bruno Luong 2020 年 11 月 16 日
function out = twoStats(x,y)
arguments
x = [];
y {MustBeExclusive(x,y)} = [];
end
% out = ...
end
function MustBeExclusive(varargin)
if sum(cellfun('isempty',varargin)) ~= 1
eid = 'XY:NotExclusive';
msg = 'X and Y must be exclusive.';
throwAsCaller(MException(eid,msg))
end
end
  3 件のコメント
Steven Lord
Steven Lord 2020 年 11 月 17 日
>> twoStats([], 5) % x is the "placeholder" empty []
ans =
5
>> twoStats(1, []) % y is empty
ans =
[]
>> twoStats(1) % specify only x, let y take on its default value
ans =
[]
>> twoStats(1, 2) % neither is empty, this is not valid
Error using twoStats
Invalid argument at position 2. X and Y must be exclusive.
I would consider what the condition in MustBeExclusive should be carefully. If specifying both x and y as empties is allowed you should use == 0 instead of ~= 1. Should the following work? Currently it does not.
>> twoStats([], [])
Error using twoStats
Invalid argument at position 2. X and Y must be exclusive.
cui,xingxing
cui,xingxing 2020 年 11 月 17 日
Thanks, great!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by