Compose with validateattributes

3 views (last 30 days)
Teddy Furon
Teddy Furon on 7 Mar 2011
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.

Answers (4)

Walter Roberson
Walter Roberson on 7 Mar 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

David Young
David Young on 7 Mar 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.]

Teddy Furon
Teddy Furon on 7 Mar 2011
Thanks Walter, Thanks David! I didn't miss anything: validateattributes is a pity and it needs a hack. Teddy

Jiro Doke
Jiro Doke on 7 Mar 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));

Categories

Find more on Argument Definitions in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!