I'm teaching myself the basics of MATLAB, and I'm stuck on how to create errors for functions. Here is my attempt:
function kinetic = KE(m,v)
KE = 0.5*m*v*v
%error messages
if (isempty(m))
% mass is empty
error('No mass given (argument 1)');
elseif (isempty(v))
% velocity is empty
error('No velocity given (argument 2)');
end
fprintf('The kinetic energy is %d joules\n', KE);
So if the user doesn't specify 2 variables, the function gives an error telling the user which variable they didn't specify. When I try to get this error message, MATLAB returns a generic error message:
kinetic(,3)
kinetic(,3)
|
Error: Expression or statement is incorrect--possibly unbalanced (, {, or [.
I don't know how to fix this. I've tried replacing the arguments of the isempty
with arg1
or arg2
, but it made no difference. Then I tried copying the example code at http://www.mathworks.co.uk/help/matlab/ref/error.html but it still didn't help.
How do you generate specific errors for functions of several variables?
I know this is quite a basic question, any help will be appreciated.
There are a few problems with your code:
The syntax of a function signature is
(Square brackets are optional if the function only has one output.) Here, kinetic
is the output of your function, whereas KE
is the name of the function; therefore, a call to your function has the form
KE(m,v)
not
kinetic(m,v)
The isempty
function is only meant to detect whether an array (and in MATLAB, everything is a 2D array, by default) is empty or not. You can't use it to detect whether a function call is missing arguments.
As pointed out by Oliver, KE(,v)
is not correct MATLAB syntax, and MATLAB will stop in its tracks and let the user know of her blunder before it attempts to process the function call.
What you probably want to do, here, is to define a variadic function, i.e. a function that can accept a varying number of arguments. Use varargin
and nargin
for that; for more details, look those up in the MATLAB help.
Finally, you probably want to
.*
and .^
),function kinetic = KE(varargin)
if nargin == 0
error('No mass or velocity given')
elseif nargin == 1
error('No velocity given (argument 2)')
elseif nargin == 2
m=varargin{1};
v=varargin{2};
else
error('Too many inputs')
end
KE = 0.5*m.*v.^2;
fprintf('The kinetic energy is %d joules\n', KE)