Practical 5: Function and Script M-files

Script M-file

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)