Compose with validateattributes
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi,
Using a parser, I would like to check that the input is of a given class (say 'numeric'), with given attributes (say a vector with positive entries) and also fulfills some other constraints (say it sums up to 1)
This line: p.addParamValue('w',1,@(x)validateattributes(x,{'numeric'},{'positive','vector'}))&&(abs(sum(x)-1)<10^-6));
doesn't work (or no longer work?) as validateattributes doesn't output anything when correct.
Any solution? Thanks.
0 Kommentare
Antworten (4)
Walter Roberson
am 7 Mär. 2011
There is no known good way of using a sub-expression in an anonymous function when the subexpression does not return any value.
David Young came up with a hack during a recent Puzzler; to see the form of his solution to this trick, see here
0 Kommentare
David Young
am 7 Mär. 2011
I agree that validateattributes is not general enough - I remember hitting the same difficulty. You could perhaps use a function like the following - put it in your path and call it instead of validateattributes - though it's a shame that such a ruse is necessary:
function ok = checkattributes(a, classes, attributes)
%CHECKATTRIBUTES is like VALIDATEATTRIBUTES but returns true or false
% OK = CHECKATTRIBUTES(A,CLASSES,ATTRIBUTES) takes the same arguments as
% VALIDATEATTRIBUTES, excluding the three optional arguments. However
% CHECKATTRIBUTES returns true or false when VALIDATEATTRIBUTES would
% return or throw an exception respectively.
%
% See also VALIDATEATTRIBUTES.
try
validateattributes(a, classes, attributes, 'checkattributes');
ok = true;
catch ME
if ~isempty(strfind(ME.identifier, ':checkattributes:'))
ok = false; % first argument failed the specified tests
else
rethrow(ME); % there was some other error
end
end
end
[ EDIT: Function changed to throw an error if there is something wrong with the arguments other than that the first one fails the required tests.]
0 Kommentare
Jiro Doke
am 7 Mär. 2011
Considering that you require a workaround anyway, I might go with this for your specific case:
p.addParamValue('w',1, @(x) isnumeric(x) && all(x>0) && ...
isvector(x) && (abs(sum(x)-1)<10^-6));
0 Kommentare
Siehe auch
Kategorien
Mehr zu Introduction to Installation and Licensing 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!