Search code examples
matlaberror-reportingvariadic-functions

How can I report custom errors when a function call is missing some arguments?


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.


Solution

  • There are a few problems with your code:

    1. The syntax of a function signature is

      enter image description here

      (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)
      
    2. 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.

    3. 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

    • vectorize your function, i.e. make it compatible with vector inputs, by using entrywise operators (.* and .^),
    • prevent results from being printed in the Command Window, by terminating all assignment statements with a semicolon.

    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)