Practical 5: Function and Script M-files

Site: learnonline
Course: MATLAB
Book: Practical 5: Function and Script M-files
Printed by: Guest user
Date: Wednesday, 3 July 2024, 3:51 PM

Description

MATLAB Short Course

Practical 5

Function and Script M-files

  • Understand the purpose of function M-files
  • Be able to create a function M-file
  • Be able to use commands that operate on functions, such as fzero and fplot.
  • Create function files from some provided code.

     

     

    Working through this Practical

    Go through this practical at your own pace and learn about the MATLAB environment in more detail.

    • The exercises are indented and on separate pages with shaded areas. Do these!
    • Ask your MATLAB eTutor if you have any questions or need advice using the Practical's Forum
    • MATLAB code will always be denoted by the Courier font.
    • An arrow > at the start of the line in an exercise indicates an activity for you to complete.
    • Use the arrows on the top right and bottom right of this display to move between pages, or select a page using the left hand navigation pane.
    • You can also print this resource as a single document (using the print icon in 1.9 or the Admin section in 2.5/2.6).

    Please submit your responses to the activities within this practical for formative feedback from your MATLAB eTutor. This word document template can be used to prepare your responses for submission.

    Script M-file

    We discussed M-files as early as in Practical 2.

    Generally speaking, script M-file is a list of commands (programming code) saved in one document.

    Some advantages:

    • Easy to use: you can run all the commands in your file by hitting one key.
    • No need to re-type or re-run lengthy code.

    Disadvantages:

    • Values from the script M-file can’t be easily assigned to variables in the Command Window. You must open, edit and save the M-file to edit values.

    Creating M-file

     

    Exercise

    > The following script M-file finds the value of the function at y= sin x + x3 at x = 3.

    % exercise1script.m

    x = 3

    y = sin(x) + x^3

    > Run this M-file by typing the following in the Command Window:

    exercise1script

    > Then update the M-file to find the value of f(x) for x = 4, 5, 6.

    Quite often we need to be able to calculate the value of a function y=f(x) for any value of x. Obviously, it is not practical to change value of x each time. For this purpose MATLAB has a special type of M-file, called M-function.

    Properties of Function M-Files

    A MATLAB file of a special format that contains code with optional inputs and outputs is called function M-file.

    Some advantages:

    • Functions can be called from inside of other script and function M-files.
    • Inputs allow variable values to be modified when calling the function (eg from the Command Window).
    • Outputs can be assigned to other variables at the Command Window or within a separate M-file.

    Disadvantages:

    • A slight disadvantage with a function M-file is that you must follow the prescribed format, or else it won’t run correctly. Once you get the hang of that, you will see they are often very useful.

    Exercise

    > The following function M-file finds the value of the function f(x) = sin x + x3 for any value of x. Type it in and save as exercise1func.m in your Current Directory

    % <insert your name and the date here>

    % exercise1func.m

    % input: x

    % output: p, solved in terms of x

    function p = exercise1func(x) %Note special format!

    p = sin(x) + x^3

    > Call this M-file from the Command Window using the following command and then update it to find the value of for p(x) for x=3, 4, 5, 6.

    exercise1func(3) % returns value for x = 3

    > Consider the case, when the variable x is an array [3 4 5 6]. Modify your function M-file so, that it will be able to work with arrays.

       

      Constructing Function M-files

      Function M-files allow you to define, construct and store your own functions.

      Why would I want to do that? You may want to create a function that plots a graph with certain fixed parameters, or create a complex equation that you will call often, or even, you may want to create a modified version of an existing function, such as a random number generator that creates numbers with values between 100 and 200 instead of 0 and 1.

      First, let’s recall some of the in-built MATLAB functions you have already used. If you type command help <name of the function> , such as help abs, in the Command Window, MATLAB will print description and correct syntax of this function. These functions have a few things in common and a few differences.

      wink Coding Tip: If the function you use does not work, try to type help <name of the function> to check for correct syntax. This may also help you immensely during the MATLAB test.

      Function: y = abs(x)

      Description: Assigns the value x to y if x is non-negative, or –x if x is negative.

      Input: 1 number: x

      Output: 1 number: either x or –x

       

      Function: y=rem(a,b)

      Description: Assigns the remainder of a/b to y

      Input: 2 numbers: a is the numerator, b is the denominator

      Output: 1 number: remainder of a/b

       

      Function: plot(xArray,yArray)

      Description: Plots a graph, given an array of x-coordinates, xArray, and an array of y-coordinates, yArray.

      Input: 2 arrays of equal length: xArray, yArray.

      Note: there can be many additional optional inputs.

      Output: A graph.

       

      Exercise: Determining the Inputs & Outputs

      > For the following function (which you may recall from the first practical), use MATLAB to help you write the description, inputs and outputs.

      Function: round(a)

      Description: _________________________________________

      Inputs: _________________________________________

      Outputs: _________________________________________

      > Exercise: Creating a Customised Random Number Generator

      > Create a function M-file called myRand.m that outputs a random number between the inputted values of minRand and maxRand by adding code in the starred lines.

      The MATLAB rand function returns a random value between 0 and 1. You will need to use this function as well as calculating the scale and offset values.

      Example: If you want to find a number between 3 and 10, your scale is 7 and your offset is 3.

      % <insert your name and the date here>

      % myRand.m

      % inputs: minRand, maxRand

      % outputs: y, a random number with value between

      % minRand & maxRand

       

      function y = myRand(minRand, maxRand)

      % **calculate the scale**

      % **calculate the offset**

      % **calculate y, using your scale, offset and %MATLAB’s rand function**

      Note: Save your function in the Current Directory, otherwise you will need to switch to the directory you saved your function in or type in a full path.

        > Type in the following lines to call this function from your Command Window and verify that it works.

        myRand(1,10)

        myRand(100,100+1)

        myRand(3,pi)

        myRand(20)

        myRand(20,1)

        > How do you think your function should handle the last two entries? You may need to edit your function to accommodate inputs of this form or generate message about the error.

        Steps to Create

        Steps for creating function M-files

        1. The function name and its M-file name must be identical (except that the M-file must end with .m).

        2. The first executable statement must be a function declaration of the form

        function <outputVariables> = <functionName>(<inputVariables>)

        Exercise

        > One of the following function declarations has been taken from the MATLAB rem.m function M-file. Determine which one must be correct declaration:

        function rem = remainder(x,y)

        function out = rem(x,y)

        out = function rem(x,y)

        function out(x,y) = rem(x,y)

          Exercise: Writing Function Declarations

          Write down the <outputVariables>, <functionName> and <InputVariables> for the two function M-files from the previous exercises and verify they match the function declaration statement.

          Function M-file 1: p(x) = sin x + x3

          Function Name: _______________________

          Output Variables: _______________________

          Input Variables: _______________________

          Function M-file 2: Creating a Customised Random Number Generator

          Function Name: _______________________

          Output Variables: _______________________

          Input Variables: _______________________

           

          Exercises

           

          Exercise: Creating a Function M-file

          > Follow steps below to create a simple function M-file that computes and outputs the nth power of 2, 2n, where n is a number specified each time the function M-file is run.

          1. Create a blank M-file and save it as twoN.m

          2. What should go at the top of every M-file? Add in header comments. This time, make sure you include the function description, inputs and outputs as well as your name and the date.

          3. Type the function declaration into your file called twoN.m

          function <outputVariables> = <functionName>(<inputVariables>)

          a) replace <function Name> with twoN

          b) decide upon an appropriate input variable name. In this case you may call it simply n.

          c) decide upon an output variable name. The name y will be used in this case.

          (In other examples you could use fn, f_n or another name of your choice as an output variable name.)

          Important: Every output variable must be assigned a value within your code.

          4. Now, you need to write your code. This function is pretty simple, so the code should only contain the following line:

          y=2^n

          Note: if you have used different input/output variable names, you must change y to match your output variable name and n to match your input variable name.

          5. OK, now you’re ready to save and test your function M-file. After saving, make sure that your Current Directory matches the one you saved your M-file in.

          6. Run the following lines in the Command Window to verify your function M-file works.

          twoTo8 = twoN(8)

          newNumber = twoN(5)

          squareOfTwo = twoN(2)

          twoN(9)

          rootOfPower = twoN(5)^(1/2)

          twoN %Why this does not work?

            Exercise: Writing your Own Function M-file

            > Create a function M-file called quadRoots to find the roots of quadratic polynomials of the form y=ax2+bx+c

            Its inputs will be the coefficients a, b and c.

            Its outputs will be the two roots, r1 and r2 and calculated by the formula:

            r_{1},r_{2}= \frac{-b \pm  \sqrt{b^{2}-4ac} }{2a}

            Test quadRoots in the Command Window with the following three polynomials:

            y=x^{2}+3x+2 (ans r1=-1, r2=-2)

            y=x^{2}+6x+10 (ans r1=-3+i, r2=-3-i)

            y=x^{2}+6x+13 (ans r1=-3+2i, r2=-3-2i)

             

             

            Return statements

            Return statements can be used to break the flow of execution of a function.

            Example:

            % indexOf: a function that finds the first index of a given number

            % in an array. If the number is not in the array, the function

            % outputs the index as -1.

            % Inputs: a number, an array

            % Outputs: an array index or -1 (means there is no such number in

            % your input)

            function position = indexOf(value, inputArray)

            position = -1; % sets index to -1, number not yet found in array

            for i = 1:length(inputArray)

            i % this line shows how many times the for loop runs

            if value == inputArray(i)

            position = i;

            return; % return stops the loop if the number is % found

            end

            end

             

            Exercise: Using Return Statements

            > Put the indexOf.m M-file in your Current Directory.

            > Test it with the following commands in your Command Window:

            idx = indexOf(8, [1, -1, 1, 4])

            idx = indexOf(8, [1, 1, 8, 1, 8])

            i=2

            xArray = [1, 2, 5, 7]

            idx = indexOf(i, xArray)

            > Disable the return statement by adding a comment sign, %. Re-test the function to see how many times the for- loop runs without it.

             

              wink Coding Tip: Make sure you save each time you edit your function.

               

              Functions on Functions

              Suppose a function y = demoFun(x) has been defined in a function M-file demoFun.m

              fplot(@demoFun,[a b]) Plots the function for a ≤ x ≤ b without setting up arrays
              fzero(@demoFun,[a b])

              Finds one value of x for demoFun(x) = 0 provided that the signs of demoFun(a) and demoFun(b) are opposite.

              fzero(@demoFun,c) Finds one value of x for demoFun(x) = 0 by starting a search at x = c
              fminbnd(@demoFun,a,b)

              Finds the coordinates of a minimum point of demoFun(x) at the interval
              a≤x≤b

              quadl(@demoFun,a,b)

              Finds an accurate value for  \int_{a}^{b}y \left(x\right)\,dx

              Note: quadl uses arrays, so therefore you must set your function up treating x as an array and so using the dot notation for operations.

               

              Exercise: Using Functions

              1. Create a function M-file called myCubic.m whose output is the value of the function y=x^{3}+2x^{2}-5x-8

              Input: x

              Output: y

              > Verify that this function works by checking that myCubic(-5)=-58 and myCubic(5)=142

              2. Create a script M-file called cubicExercise.m that contains the following five cells with code that:

              a) plots myCubic(x) between the values of [-5, 5],

              b) finds a local minimum of myCubic(x), located between 0 and 5,

              c) finds the all three roots of myCubic(x) using appropriate intervals

              [a,b]

              d) finds the value of the definite integral of myCubic(x) between -5 and 5.

              Hint: You will need to use the array dot notation so you can use the quadl function to calculate the integral of y.

              3. Make sure cubicExercise.m is marked up using cell formatting and publish it.

               

                 

                Questions?

                You may also wish to discuss these questions within the Practical 5 forum, also embedded below. If you think you know the answer, you are welcome to respond.

                 

                Submit

                Please submit your response to Practical 5 for feedback (also embedded below). Use this word document as a template.