Functions Previous Contents Next

5   Functions

There are several ways you can use functions in MATLAB. There are built-in functions such as the sine and cosine functions, there are special means to deal with polynomials, there is the ability to work with symbolic functions and you can define your own functions using function m-files.

5.1   Built-in functions

Listed below are some of the basic functions built into MATLAB.
First the standard trigonometric functions , exponential functions and logarithmic functions.

MATLAB notation Mathematical notation Meaning of the operation
sqrt(x) x square root
abs(x) |x| absolute value
sign(x)   sign of x (+1, -1, or 0)
exp(x) ex exponential function
log(x) ln x natural logarithm
log10(x) log10x logarithm base 10
sin(x) sin x sine
cos(x) cos x cosine
tan(x) tan x tangent
asin(x) sin-1 x inverse sine
acos(x) cos-1 x inverse cosine
atan(x) tan-1 x inverse tangent


Here are some functions that make the display of numbers nicer:

  • format . Typical ones can be either short, long, or rat. For example the command >> format rat will cause the display to use fractions when appropriate
Here are some functions which are useful for dealing with vectors or matrices
  • colon-operator the construct a:h:b we'll call the semicolon operator. It generates a vector of numbers between a and b of step size h.
  • cross The cross command find the cross product between 2 three-dimensional vectors.

  • dot The dot command find the dot product between two vectors.
  • dot-operator The ``dot'' or period before an operator such as * for multiplication, or ``/'' for division or ``^'' for exponentiation. Tells MATLAB to operate ``element by element'' or ``point by point''. For an example look at a dot operator example

  • help The help command accesses MATLAB's built-in help facility. To try it out try the command: help plot.
  • prod The prod command takes the product of a list of numbers, when given a matrix it takes the product of each column returning a column vector. Here is how one could implement the factorial command, n!:
    >> n = 10; prod(1:n)            % returns 10! = 3628800 = 10*9*8*...*1
    
  • roots The roots command find zeroes of a polynomial. Click here to see an example.

  • sum The sum command adds the entries in a list or the columns in a matrix. For example, let's see that the sum 1 + 22 + 32 + ··· + n2 is a perfect square when n = 24.
    >> n=1:24;                      % thenumber 1 through 24
    >> a = sum(n.^2);               % need a dot as n is a list
    >> sqrt(a)
    ans = 70                        % a perfect square
    
    Except for n=1 this is the only n for which this is true. Here is an example to simulate the number of heads in 100 coin tosses 250 times.
    >> r = rand(100,250);           % 100 random numbers in [0,1] 250 times
    >> r = floor(r+.5);             % takes integer part of r + .5
                                    % this is a number 0 or 1 with equal
                                    % chance
    >> a = sum(r);                  % adds down the columns, giving 250
                                    % numbers
    >> hist(a);                     % plot a histogram -- bell shaped
    
  • transpose-operator the symbol ' or single-quote indicates transpose. It switches a row vector into a column vector or vice versa.
Here are some MATLAB commands for plotting functions:
  • cylinder Despite its name, this command plots a surface of revolution of a curve around the z-axis. The curve is entered in a vector of radius values. (That is you plot the surface given by x2 + y2 = f(z)2.) To plot a sphere you could enter the commands
    >> z = -1:.1:1;
    >> r = sqrt(1 - z.^2);
    >> cylinder(r).
    
  • grid puts a grid up during a plot command.
  • linspace The command linspace(a,b,n) generates n points equally spaced over the closed interval [a,b]. Note that if you wish to divide an interval into 10 equal subintervals, you need 11 points including the end points of the interval. If you omit n then the command linspace(a,b) generates 100 equally spaced points over [a,b]. Similar to colon-operator .

  • meshgrid Like the linspace command, this creates a matrix of x and y values to be used in plotting three-dimensional graphs. It is used in the following manner:
    >> [x,y] = meshgrid(-1:.1:1,-pi,:.1,pi);
    
  • plot The plot command is used to plot lists of data. In its simplest use if x and y are the same size list, then plot(x,y) plots the x list verse the y list. More advanced features are possible. See the help page or click here.
  • plot3 The three-dimensional plotting function. The command plots3(x,y,z) plots the points (xi,yi,zi) with a straight line connecting the point (xi,yi,zi) to (xi+1,yi+1,zi+1).
  • sphere Will plot a sphere. See help sphere for more info.
  • surf Creates a graph of a surface. It is called by >> surf(x,y,z), where x, y and z are matrices. To use it you would typically create the values of x and y with the meshgrid command, and the value of z as a function of x and y.
  • view This command changes the view or perspective of a three dimensional graph. You can call it with two angles or a vector. The vector is a three-dimensional vector that points in the opposite direction than where you are looking from. For example, view([1,1,1]) will give a view of the origin as if you are looking from the point (1,1,1).
  • zoom The zoom command is usually followed by either an on or off. When on it allows you to explore the current plot with your mouse. ``Dragging'' out a window will force MATLAB to ``zoom in'' on that area. To undo this double click the mouse. As well, clicking in an area will force a similar effect.

5.2   Polynomials

There are a number of MATLAB commands that allow one to work easily with polynomials. For example: conv , deconv , poly , polyder , polyfit , polyval , roots . See the help commands if you can't find a definition.

To use any of these built-in functions you need to be familiar with the shorthand convention MATLAB uses to store polynomials. Since a polynomial is determined by its coefficients (why?), it is only necessary to keep track of these numbers not the powers of x. For example, 15x3 - 6x + 12 is associated with the list (15,0,-6,12). Now a list in MATLAB can be a row vector or a column vector. MATLAB takes the convention that polynomials will be row vectors so the polynomial above would be
p = [15,0,-6,12]                % notice commas not semicolons -- row vector
If we wanted to find the roots of the polynomial 15x3 - 6x + 12, or the solutions to the equation 15x3 - 6x + 12=0 we could use the MATLAB command roots as follows
>> roots(p)                     % notice answer is a column vector
ans =

  -1.07097 + 0.00000i           % this is the real number -1.07097
   0.53549 + 0.67841i           % these two are complex conjugates
   0.53549 - 0.67841i
A general fact about polynomials tells us that a 3rd degree polynomial will have 3 roots. So we start with a row vector with 4 entries, and we get back a column vector with 3 entries.

5.3   Function m-files

If you want to explore many functions, it is tedious to keep retyping and/or using the Up Arrow key to repeat commands. Here we learn to simplify our work with script files and m-files .

A script file will be a file that stores a sequence of keystrokes that makes it easier to reuse, or easier to edit if it is complicated.

An m-file (or function m-file) in MATLAB is the way subroutines are implemented. Knowledge of how to create m-files can make MATLAB a very powerful tool for studying mathematics.

  • SAVING COMMAND SEQUENCES IN M-FILES OR SCRIPT FILES

    if you are working on the CSI network, and you do not already have a diskette in drive A you need to inform MATLAB where to find your personal script files. Try the command
    >.  path(path,'a:\');           % or restart MATLAB with diskette in a:
    
    To create a new script file in Windows 3.1:
    • Open the file menu (by clicking on FILE on the menu bar with the left mouse button);
    • click on NEW in the menu; a sub menu will appear;
    • click on the M-FILE option.

      This will open a new untitled file in the Notepad editor (it is possible to set up MATLAB to use other editors). You should resize and arrange your windows so that it is easy to go back and forth between the MATLAB Command window and the Notepad window.

    • You are know ready to go!


    Script file exampleeg:script-file

    Type in the following lines in the Notepad window. (Nothing will happen in the MATLAB window.) After typing a couple lines, choose Save As from the Notepad File menu. Save the file under the name ``limit.m'': you must use the extension ``.m'' or MATLAB will not recognize it. Choose Save from the File menu when you're done, but leave the Notepad window open. You will have written a program in the MATLAB language.

    This program uses a shortcut: instead of writing x=[.1 .01 .001 ...], we write x=(.1).*(n) where n=1,2,3,...

    %%%% this file should be saved as limit.m
    %%%% a % (percent sign) makes a comment to the end of the line
    clear                           % gets rid of old definitions
    format long                     % gives more digits in the answer
    n= 1:1:6;                       % the numbers 1 though 6
    x=-(.1).^n;                     % the numbers 10^(-1) through 10^(-6)
    y=sin(x)./x;     
    [x;y]'                          % limit from left in a table form   
    x=(.1).^n;                      % or use x = -x with x above
    y=sin(x)./x;
    [x;y]'                          % limit from right in a table form
    
    (Recall: MATLAB ignores text following a %.)

    After saving the file, return to the MATLAB Command window (by clicking somewhere inside the window), and type
    >> limit                        % evaluates the file limit.m
    
    Note that you don't type the ``.m''. MATLAB should begin to execute the commands just as if you had typed them in the Command window.

    If you made an error while typing the file limit.m, MATLAB will halt on the line with the error and print out an error message. Simply return to the Notepad window, fix the error, Save the file, and try typing limit again in the Command window. If you already closed the Notepad window, Click on Open in the File menu (in the Command window), find limit.m in the file list and reopen the file.

    Note: MATLAB does not find syntax errors before running the program since it uses an interpreter rather than a compiler (like C or Pascal).

    moral: MATLAB beeps when it is trying to get your attention. This means it can't figure out what you mean. Pay attention and find out why it beeped, its just trying to help you.

  • Function m-files

    In order to create functions in MATLAB we need to have an understanding of how MATLAB handles the following computer related concepts


    • Format of the m-file: what is the syntax.
    • Input and Output of data: how to pass arguments
    • looping: for loops
    • Conditional expressions: how to direct the flow
    • Calling the function from MATLAB.

    Let's look first at an example to illustrate these points. The function n! in mathematics is shorthand for 1 · 2 ··· n. In MATLAB there is no built-in factorial function. Lets define one as fact. our function fact should have as its input a non-negative integer, and its output should be the factorial.
    function y = fact(n)            % the function word is a non-comment. y
                                    % is the name of the output variable
                                    % and n is the name the m-file gives
                                    % to the input variable.
      if n < 0
                                    % this line prints out an error message
        fprintf("factorial needs a non-negative integer\n");
                                    % returns if there is an error
        return
      end
      
      y = 1;                        % initialize the value of y
    
      for i = 1:n                   % a loop
        y = y*i;
      end                           % end the loop
    
    Let's analyze the important lines.
    • function y = fact(n)
      
      This line follows the syntax of a function m-file. The first word if the keyword function. Then the return value or output, in this case the value of y. What does the return value equal, the function name without the .m extension, in this case fact, and then the input, in this case n. Hence when n is referred to in the file, it refers to the input value.
    • if n < 0
      
      This is the syntax for a conditional test. The simplest usage is
      if (CONDITION)
        THEN-BODY
      end          
      
      as in the factorial example. In general, it can be
      if (CONDITION)
        THEN-BODY
      elseif (CONDITION)
        ELSEIF-BODY
      else
        ELSE-BODY
      end
      
      An example in general can be given with the heavyside function:
      function y = h(x)               % save this a h.m
      if x < 0
        y = -1;                       % so h(-5) = -1
      elseif x = 0
        y = 0;                        % h(0) = 0
      elsif x > 0                     % and h(5) = 1
        y = 1;
      end
      
    • fprintf(stderr,"factorial needs a non-negative integer\n");
      
      This is one way to pass a message back to MATLAB. The command fprintf is the print function, the word stderr tells MATLAB where to print the upcoming message (in this case where error messages go), and the line in quotes is the message. The \n is the end of line character.

    • for i = 1:n     
      
      This is main looping construct. This increases the value of i from 1 to n where n is the number given to fact when the function is called. The general syntax for a for loop is
      for x = array
        COMMANDS
      end
      
      Whew, that was a lot of work considering the following commands will find the factorial:

      >> prod(1:n);                   % product of 1,2...n
      >> gamma(n+1);                  % gamma function is related to factorial
      
      The array can be quite general. Here are some examples which can be run from the command line, or put into an m-file
      >> tot = 0;                     % our total
      >> for i = 1:2:100              % just the odd numbers
      >  tot = tot + i;               % you may have a different prompt
      >> end; tot                     % prints sum of odd numbers between 1
                                      % and 99
      
      >> x = randn(1,100);            % a list of 100 normally distributed
                                      % random numbers 
      >> temp = 1:100;                % the number 1 through 100
      >> for i = temp(x < -2 | x > 2) % these are outliers in the data
      >   x(i) = 0                    % make outliers 0
      >> end
      
      The last example uses some a complicated way to get the array or list of numbers to index over. It takes only those indices for the list x which have x-values less than -2 or bigger than 2.

      Another looping construct is the while command. This has the form
      while (CONDITION)
        BODY
      end
      
      An simple example could be to construct the first n Fibonacci numbers. These numbers are 1,1,2,3,5,8,13,21,34,55 if n is 10.
      function fib = fib(n)           % save as fib.m. return name same as
                                      % function name. That's okay!
      fib = ones (1, n);              % fib = [1,1,1,1,1,1,1,1,1,1] if n=10
      i = 3;
      while (i <= n)
        fib (i) = fib (i-1) + fib (i-2); % 1+1=2, 1+2=3, 2+3=5, 3+5=8 ...
        i=i+1;                        % increment i
      end       
      
      The while loops keeps looping until the condition that i be less than or equal to n is no longer true. The command ones is a simple way of making a sequence of all ones. Of course we should check that n is an integer bigger than 3. Don't forget to increment your expression or you'll find an infinite loop. (you can use the control-c key sequence to disable this.
      >> i = 1;while i < 2
      >  fprintf(``Help me! I'm stuck in an endless loop\n'')
      >> end
      

    Some more examples of m-files:
    • Evaluating functions from mathematics.

      Suppose you wanted to evaluate the function f(x) several times in the course of a mathematical experiment. One way to type less is with an m-file
      function y = f(x)               % save as f.m
      
      y = 1 - x.^2/2 + x.^4/4;        % 5 terms in Taylor series for cosine
                                      % x. Notice the dots
      
      This was written so that both x and y could be lists of numbers. To use this we might do this in a MATLAB session
      >> x = linspace(0,pi);
      >> y = f(x);z=cos(x);           % pass f(x) a list of numbers. No
                                      % problem.
      >> plot(x,y,x,z)                % compare approximation to cosine x
      >> h=.01, difquo = (f(x+h) - f(x))/h % compute difference quotient
      >> plot(x,difquo,x,sin(x))      % compare difference quotient.
      
    • Writing your own ezplot .

      Suppose you want to make plotting of a function simple, but you don't want to use ezplot as it works only for symbolic functions. Here is a simple m-file you could use. Can you think of any extensions you might make?
      function y = myezplot(f,a,b)
      
      %% myezplot: called with a function defined in an m-file, a and b
      %%graphs the function f defined in f.m over the range of
      %% values specified by the range [a,b]. If a and b are omitted it
      %% takes the interval [-5,5] as a default. 
      
      if nargin = 1
        a=-5;b=5
      end
      
      for x = linspace(a,b)        % loop over x in [a,b]
        y(i) = feval(f,i)          % call the function in f.m. Needs to use
                                   % feval
      end
      
      plot(x,y);
      
      To call this function you would first define your function in a m-file, say yourfunc.m, then you would use the command
      >> myezplot(yourfunc,0,3)              % plots yourfunc between 0 and 3
      
      This example uses the variable nargin which is a count of the number of arguments in the input. As well it shows how you can pass a function name to a function. You need to use the command feval to evaluate the function.

Previous Contents Next