Examples

  1. First consider a simple function, from a programming point of view, but involving a complicated formula. The function is the mathematical expression

    ""

    or an equivalent form that involves fewer multiplications:

    ""

    This function is a rather good approximation to the error function that you have encountered previously in this course. The approximation is only valid for nonnegative values of x. Suppose you wanted to use this function in your calculations. One way to do it is to type it in carefully once and then copy and paste it wherever else you need it. However, that is error prone and will make the code rather difficult to read. A better solution is to write a function error_approx to compute the value. Then whenever you wish to use the function, you can call error_approx to get the value.

    Another reason to use a function is that the formula given for the approximation is only valid for nonnegative values of x, but it can be extended to all values of x with the formula e(x)=-e(|x|) for negative values of x. This can be included in our function to extend our approximation to negative values of the input.

    Define a function that evaluates the second version of the formula above:

    Here is one way to implement the Error Approximation function. Type these lines of code in a Matlab m-file and save the file with the name error_approx.m.

    function val = error_approx( x ) 
    % error_approx - computes a good approximation to the error function.
    a = abs(x) ; 
    s = sign(x) ; 
    val = s*(1 - 1/( 1 + (0.278393 + (0.230389 ... 
        + (0.000972 + 0.078108*a)*a)*a)*a)^4 );
    
    We now go through the operations in this function line by line..
    • The first word in the file, function, indicates that this file contains a function definition. Next is the basic information required for functions: the name of the output or return value, an equal sign, the name of the function, open parenthesis, the names of the input parameters, close parenthesis. This function has the name error_approx and it has one input parameter, declared as x, and one output value, declared as val. Remember: The first line of each Matlab function always has this basic form.
    • Comments describing the function are included starting on the second line. These comments give information about the function and how to use it, inputs and output value, to any users of the function. A user can display these comments by executing:
      help functionName

      If you include comments, the Matlab command:

           >> help error_approx
             error_approx - computes a good approximation to the error function.
      

      will print out your comment lines so that the user can find out what the function does and how to call it. Comments also make it easier for anyone, including yourself, who reads the file to understand how the function works.

    • The next lines compute the function by initializing the local variables a and s with values. We use the ellipsis (...) to indicate that the formula is continued to the next line. This is used to make complicated expressions easier to read. The value of val, which is specified in the first line as the name of the output of the function, must be computed in the function. Usually it is the last quantity computed.

    The parameter x and the return value val used in the definition of the function are independent of the variable names used to call the function. Call the function using a value or variable name that have been assigned a value.

         c = error_approx( 3.14159 ) 
         p = 1.25 ; 
         r = error_approx( p ) 
         y = error_approx( pi ) 

    The variables declared and used inside of the function definition structure are all local to the function. They have no connection to variables with the same name in other program units. That means that two variables with the same name height contain different values if one is inside of one function and the other is used inside of a different script or function.

    You can check how good the approximation computed by error_approx is by comparing the results you get from it to the results you get from using the Matlab function erf() which computes the error function using a much better approximation. Actually, all the functions such as sin and cos that Matlab has are approximations. They are, however, very good approximations.

    Notice that by putting the computation of the mathematical expression in a function, the remainder of the code will be much more readable. The more readable the code is, the easier it is for you to understand what is going on.

  2. The exponential integral function is given in this formula. ""

    Copy and paste the Matlab commands that follow into the file expintApprox.m.

         function e = expintApprox( x ) 
         % This function computes an approximation to the exponential integral
         % e ~ integral from x to infinity of exp(-t)/t
    
         % Uses the log() plus a polynomial for small values of x.
         if x < 1 
            e = -log(x)- 0.57721566 + x.*(0.99999193 ... 
                - x.*(0.24991055 - x.*(0.05519968 ...
                - x.*(0.00976004 - x.* 0.00107857 )))) ;
    
         % Uses a ratio of polynomials for larger values of x.
         else 
            e = exp(-x).* (0.250621 + x.*( 2.334733 + x )) ./ ...
                ((1.681534 + x.*( 3.330657 + x )).*x ) ;
         end

    Test this function on the vector [ 0.5 , 1.5 ]. Compare the values returned by our approximation with the values returned by expint( ) for these same values. You may want to change the display format that is used. Use the command format long to see the difference between the two functions. You can enter the command format short to restore the default format. Use the default format for homework and quizzes, unless explicitly asked to use the long format.

    >> format long
    >> expintApprox([ 0.5 , 1.5 ])
    
    ans =
    
       0.56253779996729   0.10001942021269
    
    >> expint([0.5,1.5])
    
    ans =
    
       0.55977359477616   0.10001958240663
    
    >> format short
    >> 
    

    Our Matlab function, expintApprox( ), computes a good approximation to the exponential integral function. Notice that the function depends on x, and is computed by integrating another function from x to infinity. The exponential integral function arises in a number of engineering and scientific applications.

    Again, take some time to notice each part of the function script. There is the first line that specifies that this is a function and gives the name of the function. It also specifies the inputs and outputs.

    The comments are not essential, but are very useful in non-trivial functions. They help us understand what the function does and gives other information.

    The lines that compute the function are next. Don't worry about the if and elsestatements just yet. We will be covering those programming constructs in detail later in the course. For now, just understand that it is possible to define functions such that in one invocation (call) the return value is computed one way; while on a different call with a different input value, the result may be computed a different way. The if statement makes this possible.

    Matlab has a built-in function that computes the exponential integral function to full precision and it is called expint( ). The approximation our formula provides is quite accurate, but not quite as good as the Matlab function.

  3. Plot the functions and the difference between the functions.
         clear; clf;
         x = 0.1 : 0.2 : 5 ;
    
         for k = 1: length(x)
             yA(k) = expintApprox( x(k) ) ;
         end
    
         yB = expint( x ) ;
         yD = yB - yA ;
    
         subplot(2,1,1), plot( x, yA , 'r', x, yB, 'b' )
         subplot(2,1,2), plot( x, yD )

    Again, don't worrry about how this code works. We will cover iteration and the for statement later in the course.

    Do notice that the difference is less than 10-5. The functions should be indistinguishable to plotting accuracy.