Creating my own error within a program
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I just have a quick question... So I'm writing a program that adapts to whatever variable names and what values they hold. I wanted to add a bit that checks the user entered variables quickly using isvarname to ensure that they were all viable names before too much time and memory was wasted doing other things. This I have down. What I need clarification on, and possibly a step-by-step guide to, is writing a custom error message to display and trigger a catch block.
Do I just need to write out the error( '...' , '...' ) bit and call it good or do I need additional code there for matlab to actually catch the error?
Thanks in advance for the help,
Zach
0 commentaires
Réponses (1)
Matt Fig
le 14 Juin 2011
Is your program a function? If so, then it doesn't matter what variable names the user passes, because your function will have its own variable names. For example, consider this function:
function b = myfun(a)
b = a;
Now when the user calls this with say,
myfun(var_name)
Your function will never see var_name, only a.
If you're using a script, then MATLAB won't let the user use a bad varname anyway. For example, try to make this variable:
1f = 5; % Errors.
For help with using the ERROR function, see the help!
help error
help try
2 commentaires
Matt Fig
le 14 Juin 2011
function b = myfun(varargin)
% Describe in detail how many arguments can be accepted,
% and the order of these arguments. In this example, say
% the user can input up to two values.
N = nargin; % Tell how many inputs the user provided.
if N==0;
a = 1; % Default values of two inputs a and c
c = 4;
elseif N==1
a = varargin{1};
c = 4;
elseif N==2
a = varargin{1};
c = varargin{2};
else
error('Too many inputs')
end
% Rest of the code using a and c....
Voir également
Catégories
En savoir plus sur Scope Variables and Generate Names dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!