Todo User-Defined Functions - Bad Examples
Todo User-Defined Functions - Bad Examples
where
function_name is the name of the function (which must also be the name of the
m-file it is in)
return_value is the name of the output
parameters are the names of the inputs, separated by commas
Each function must be in its own m-file and the name of that m-file must be the same as
the name of the function. Note that the name of the return value (output) and the names
of the parameters are the programmer's choice (and can be the same as names used in
other functions or scripts).
All functions in Matlab are defined this way, including the ones provided by Matlab.
This means that somewhere among the files that Matlab uses as it runs are cos.m, sin.m,
and exp.m (among many others) which contain the definitions for the cosine, sine, and
exponential functions, respectively.
The following examples show several incorrect functions followed by a correct version of
the function. Each function is supposed to cube the input (assuming the input is a scalar
value).
Bad Example 1:
function c = cube(x)
y = x^3 ; % The value of the output c is not defined.
Bad Example 2:
Bad Example 3:
function c = cube(x)
c = x^3 ;