User Defined Functions


Functions are defined in .m files that have same file name as that of the function being defined. For example, a function vNorm must be defined in a file called vNorm.m.

A function definition has the following structure

function [ret1, ret2, ret3,...] = fun(arg1, arg2, arg3,...)
Matlab statements 
        *
        *
ret1 = ...
ret2 = ...
ret3 = ...

This defines a function named fun, with input arguments arg1, arg2, arg3, ... and returns arguments ret1,ret2,ret3,....

No explicit return statement is required in a function.

In addtion to invoking a function by fun(arg1, arg2, arg3...), one can also invoke functions using the feval command. For example, a user defined function sin2 can be evaluted as

>> sin2(1.0)

or

>> feval('sin2',1.0)

One can evaluate a function defined by a string using the eval command. See the samples for how to do this.


Samples

% Defining a sin(x)^2 function (in a file called sin2.m)

function [y] = sin2(x)
y = sin(x).*sin(x);  % (Using .* so that the function works on vectors) 

% Using the previously defined sin2 function in the command line

  sin2(1.0)
  ans =
    0.7081

% Creating a function that plots other functions over an
% interval[a,b] (in a file plotFun.m). Note that the function
% is passed as a string and the evaluated using the feval command.

function [] = plotFun(fstring,a,b)

n = 100;                % number of panels
x = a:(b-a)/n:b;        % generate ordinates
y = feval(fstring,x);   % generate abscissas by evaluating f(...)
plot(x,y);              % create line plot 

% Invoking plotFun on the sin2 function.

 plotFun('sin2',0.0,2.0*pi);

% Creating a function that returns the norm of a vector
% as a double

function [y] = vNorm(x)
y = sqrt(x*x');

%
% Evaluating a function defined by a string
%

fstring = '(x-1)*(x-2)*(x-3)';   % function defined by a string
eval(['x = a;',fstring,';']);    % evaluate the function at x = a
y = ans;                         % set y to be the function value


UCLA Mathematics Department ©2000