How do I parse two input arguments for matching dimensions with Matlab Input Parser?
14 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Lukas
am 25 Jul. 2014
Kommentiert: Daniele Busi
am 16 Sep. 2018
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 Kommentare
Akzeptierte Antwort
Dima Lisin
am 26 Jul. 2014
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 Kommentare
Daniele Busi
am 16 Sep. 2018
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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Argument Definitions finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!