MATLAB Answers

0

validate function inputs independent of position and name

Asked by Octavian on 7 Jan 2015
Latest activity Answered by Guillaume
on 7 Jan 2015
Dear All,
I have the function f(a b c d), with a b c d inputs all structure arrays, a and b required, c and d optional. I want to validate inputs based on that a b c d are all structures (this may be redundant, see next), and/or more specifically, based on the name of some specific fields for each of the a b c d inputs, say a.fielda, b.fieldb, c.fieldc, and d.fieldd, but not the position or name of the arrays themselves (eg a b c d). Additionally, since my code uses C as intermediate, then output variable for input c, I want to make sure that if the name of c input is C, the validation will generate an error message, as I do not want c to be modified (the principle of input argument preservation). Please advise, I got stuck with using inputparser and validateattributes, I would appreciate some hands on example using info herein. Thank you,
Octavio.

  0 Comments

Sign in to comment.

1 Answer

Answer by Guillaume
on 7 Jan 2015
 Accepted Answer

A simple way to check if structure 'a' contains the fields 'fldname1' and 'fldname2':
if ~isstruct(a) || ~all(ismember({'fldname1' 'fldname2'}, fieldnames(a)))
error('input a must be a structure with field names fldname1 and fldname2');
end
If you want to check that fielda, fieldb, ... are present in at least one structure:
%check that a,b,c,d are struct first, then:
allnames = [fieldnames(a); fieldnames(b); fieldnames(c); fieldnames(d)];
if ~all(ismember({'fielda' 'fieldb' 'fieldc' 'fieldd'}, allnames))
error('at least one field wasn't supplied');
end
As for the last part of your question, it sounds like you want to do some validation based on the name of the variable that is passed to your function. It's possible (use inputname) but don't do it. You shouldn't be ditacting to the user of your function what variable names he is allowed / not allowed to use. It's just poor programming and can only lead to bugs / unexpected behaviour. In any case, unless you're using assignin you can't modify his variables, so whatever name he uses is irrelevant.

  0 Comments

Sign in to comment.