How do I parse two input arguments for matching dimensions with Matlab Input Parser?
10 次查看(过去 30 天)
显示 更早的评论
I use the Matlab Inputparser Class to validate function input, this is a minimal example:
function C = multiplyMatrix(A, B)
p = inputParser;
addRequired(p, 'A', @isnumeric); % Line A
addRequired(p, 'B', @isnumeric);
parse(p, A, B);
if size(A, 2) ~= size(B, 1) % Line B
error('Size mismatch.');
end
C = A*B;
end
How do I integrate tests spanning more than one variable (i.e. the if-statement in Line B) in the concept of the Matlab Inputparser Class? I only found out how to create tests regarding one variable (see Line A).
I am also happy about comments about the usage of this Parser in total.
(I had asked this question on stackoverflow.com before, but I feel like this is the better place to ask.)
0 个评论
采纳的回答
Dima Lisin
2014-7-26
Unfortunately, you cannot do that inside inputParser. For each parameter you can only supply a function that validates just that parameter. Any tests involving more than one parameter have to be done separately, after you call parse().
4 个评论
Daniele Busi
2018-9-16
The suggested addCombination method can only be included inside a subclass. This subclass should do the job:
classdef inputParserEx < inputParser
properties
combofuncs
combovars
end
methods
function p = inputParserEx
p.combofuncs = cell(0);
p.combovars = cell(0);
end
function addCombination(p,vars,validateFunc)
assert(isa(p,'inputParserEx'))
assert(iscellstr(vars) && isvector(vars))
assert(isa(validateFunc,'function_handle'))
assert(nargin(validateFunc) == numel(vars));
p.combofuncs{end+1} = validateFunc;
p.combovars(end+1,1) = {numel(vars)};
p.combovars(end,2:numel(vars)+1) = {vars{:}};
end
function parse(p,varargin)
assert(isa(p,'inputParserEx'))
parse@inputParser(p,varargin{:});
for c = 1:numel(p.combofuncs)
args = cell(1,p.combovars{c,1});
for v = 1:p.combovars{c,1}
assert(isfield(p.Results,p.combovars{c,1+v}),['invalid combination number ' num2str(c)]);
args{v} = p.Results.(p.combovars{c,1+v});
end
assert(p.combofuncs{c}(args{:}),['condition number ' num2str(c) ' not fulfilled']);
end
end
end
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Argument Definitions 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!