Compose with validateattributes

1 visualización (últimos 30 días)
Teddy Furon
Teddy Furon el 7 de Mzo. de 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.

Respuestas (4)

Walter Roberson
Walter Roberson el 7 de Mzo. de 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 el 7 de Mzo. de 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 el 7 de Mzo. de 2011
Thanks Walter, Thanks David! I didn't miss anything: validateattributes is a pity and it needs a hack. Teddy

Jiro Doke
Jiro Doke el 7 de Mzo. de 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));

Categorías

Más información sobre Programming en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by