Compose with validateattributes

조회 수: 8 (최근 30일)
Teddy Furon
Teddy Furon 2011년 3월 7일
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.

답변 (4개)

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

Jiro Doke
Jiro Doke 2011년 3월 7일
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));

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by