# Functions

### From ComputingForScientists

## Contents |

# 1. Functions

## 1.1. References

## 1.2. Objective

- To introduce functions in MATLAB.

## 1.3. Motivation

- Functions allow programs that are often used to be written in a short-hand form.

## 1.4. Built-In Functions

MATLAB has many common math functions. To see the list of common math functions, see the output of `help elfun`

.

To see the documentation for a given function, enter `help `

on the command line, e.g., *functionname*`help sin`

and `help sind`

.

## 1.5. Creating a function

The first step is to give the function a name. Suppose that we want to create a function that has an input of two numbers and returns the sum of their squares as the output. We want the following command

>> sumsquare(2,4)

to display

ans = 20

To create the function `sumsquare`

we need to create a file named `sumsquare.m`

and save it:

function z = sumsquare(x,y) z = x^2 + y^2;

The first line of the file distinguishes it from a script. The first line declares that this file contains a function that takes two inputs and returns one output.

Note that the name of the file is the same as the part between the `=`

and `(`

. If the file name and function name are different, the function will not work. Also, note that the variable between `function`

and `=`

is the output of the function. In this case, the variable is `z`

and it also shows up in the program as the variable that is assigned a specific value. Therefore, whatever variable you want as an output of the function has to be in the actual program. For example, the following function would not give any output because the output variables do not match:

function z = sumsquare(x,y) % Function will not work because z is never defined. s = x^2 + y^2;

To make this function valid, you would have to make sure both output variables are the same by either making them both `z`

or `s`

.

## 1.6. Example

To create a function that returns the square root of a number, you first have to create a file named `squareroot.m`

and enter:

function y = squareroot(x) y = x^0.5;

After saving the file, you can type the following on the command line:

>> squareroot(9)

## 1.7. Scope of variables in functions

The variables that you create inside of a function are not accessible outside of the function. For example, if the function is

function z = myfun(a,b,c) x = a+1; y = b+2; z = c+3; z = x+y+z;

and you use the function in a script

clear; d = myfun(1,2,3) a b c x y z

all of the commands after the second line will result in an error message. The reason is that the variables defined inside of the function may only be used inside of the function. Said another way, the **scope** of the variables defined inside of a function is that function.

## 1.8. Multiple outputs

A MATLAB function can have multiple inputs and multiple outputs. The general syntax is

function [out1,out2,...] = functionname(in1,in2,...)

For example, if the following is entered into a file named `squareroot_and_square.m`

function [a,b] = squareroot_and_square(x,y) a = x^0.5; b = y^2;

we can compute the square root and square two numbers using a single function call:

>> [xroot,xsquared] = squareroot_and_square(4,3); xroot = 2 xsquared = 9

## 1.9. Array and Matrix Inputs and Outputs

Thus far, we have only considered the case where the inputs and outputs of a function are scalars. MATLAB also allows the inputs and outputs of a function to be arrays or matrices. For example, the built-in function `sum`

takes an input of an array and returns the sum of the elements:

>> A = [1,2,3,4]; >> sum(A)

gives

ans = 10

If the input is a matrix, the function returns the sum of each column:

>> M = [1,2,3,4;1,2,3,4]; >> sum(M)

gives

ans 2 4 6 8

in this case, the output was an array instead of a scalar.

## 1.10. Procedure for Creating Functions

A good method for creating a function is to first create the code in a script. This allows you to easily debug and modify the code before placing it in a function.

For example, suppose that you wrote a program that added the square of all values in an array.

Original program:

A = [1,3,4,8,2]; s = 0; for i = [1:5] s = A(i)^2 + s; end s

In this code, it is clear that the input is and array and the output is a scalar value.

To create a function so that you could enter:

>> sumsquare([1,3,4,8,2])

and have

ans = 94

displayed, create a file named `sumsquare.m`

that contains the original program * with the assigned value of the input removed*. That is, in the function, you write code assuming that the inputs are defined.

function s = sumsquare(A) s = 0; for i = [1:5] s = A(i)^2 + s; end

>> sumsquare([1,3,4,8,2])

If the definition of the array `A`

was not omitted

function s = sumsquare(A) A = [1,3,4,8,2]; s = 0; for i = [1:5] s = A(i)^2 + s; end

and you entered this on the command line:

>> sumsquare([1,3])

would not return the `1`

. Instead, it would return ^{2} + 3^{2}`1`

because the input array ^{2}+3^{2}+4^{2}+8^{2}+2^{2}`A`

was modified.

## 1.11. Function Advantages

The primary advantage of a function is that it allows you to write less code. Suppose you were asked to sum the squares of these two arrays:

[1,3,4,8,2] [3,3,2,1,5]

You could write this:

A = [1,3,4,8,2]; s = 0; for i = [1:5] s = A(i)^2 + s; end s A = [3,3,2,1,5]; s = 0; for i = [1:5] s = A(i)^2 + s; end s

but if you had created a function:

function s = sumsquare(A) s = 0; for i = [1:5] s = A(i)^2 + s; end

you would only need to write:

>> sumsquare([1,3,4,8,2]) >> sumsquare([3,3,2,1,5])

## 1.12. Anonymous Functions

# 2. Problems

## 2.1. Built-In Functions

The description of each function is typically very terse, and it takes some practice to get used to interpreting the description.

Read the following MATLAB statements and then *using only the description of each function returned by the help function*, attempt to determine what the result will be when the statement is entered on the command line. Then check your answer by entering the command on the MATLAB command line.

sin(pi/2) + cos(2*pi) sind(pi/2) log2(16) exp(1) fix(-1.1) fix(1.1) floor(-1.1) floor(1.1) mod(210,7) rem(210,7) rem(13,2) round(5.5)

## 2.2. Built-In Functions

Write a MATLAB command that will compute the fractional part of the result of the following

*s**i**n*(47^{o}) + *c**o**s*(37^{o}) + *l**o**g*_{2}(10)

## 2.3. Built-In Functions

Write a MATLAB command that will compute the result of the following

*s**i**n*(47^{o}) + *c**o**s*(π / 3) + *l**o**g*_{10}(22)

## 2.4. Built-In Functions

Write a MATLAB command that will display a zero if a number `a`

can be divided by a number `b`

without a remainder. Test your command using `a=105`

and `b=7`

.

## 2.5. Built-In Functions

Read the text displayed when you enter `help format`

and then answer the following question.

When you start MATLAB and enter `pi`

on the command line, you see

ans = 3.1416

What command could you enter so that you see

ans = 3.141592653589793

when `pi`

is entered on the command line?

## 2.6. Simplifying a Program

Consider the following program that computes `z1`

, `z2`

, and `z3`

:

a = 1; b = 2; c = 3; z1 = a.^1.1 + b.^1.2 + c.^1.3; a = 11; b = 22; c = 33; z2 = a.^1.1 + b.^1.2 + c.^1.3; a = 0; b = 1; c = 2; z3 = a.^1.1 + b.^1.2 + c.^1.3;

Simplify this program using a function.

Answer |
---|

New program z1 = sumpow(1,2,3); z2 = sumpow(11,22,33); z3 = sumpow(0,1,2); Function (saved in file function z = sumpow(x,y,y) z = x.^1.1 + y.^1.2 + z.^1.3; |

## 2.7. Quadratic Equation

Write a function such that when

a = 1; b = 1; c = 1; x1 = solvequadratic(a,b,c); x1

is entered on the command line, the value of one of the solutions to the equation ax^{2} + bx + c = 0 is assigned to the value of `x1`

.

Save your file as `solvequadratic.m`

.

Answer |
---|

File solvequadratic.m contents: function [x1] = solvequadratic(a,b,c) x1 = (-b + sqrt(b^2 - 4*a*c))/2 to return both roots, use function [x1,x2] = solvequadratic(a,b,c) x1 = (-b + sqrt(b^2 - 4*a*c))/2 x2 = (-b + sqrt(b^2 - 4*a*c))/2 Note that MATLAB has a built-in function for solving for zeros in polynomial equations: roots([c,b,a]) will show the same values as function [x1] = solvequadratic(a,b,c) X = roots([c,b,a]); x1 = X(1); |

## 2.8. Quadratic Equation

Write a function such that when

a = 1; b = 1; c = 1; [x1,x2] = solvequadratic(a,b,c); x1 x2

is entered on the command line, the value of *both* of the solutions to the equation ax^{2} + bx + c = 0 are displayed.

Save your file as `solvequadratic2.m`

.

Answer |
---|

File solvequadratic2.m contents: function [x1,x2] = solvequadratic2(a,b,c) x1 = (-b + sqrt(b^2 - 4*a*c))/2 x2 = (-b + sqrt(b^2 - 4*a*c))/2 Note that MATLAB has a built-in function for solving for zeros in polynomial equations: roots([c,b,a]) will show the same values as function [x1,x2] = solvequadratic2(a,b,c) X = roots([c,b,a]); x1 = X(1); x2 = X(2); |

## 2.9. Product Function

Write a function named `product`

that takes three numbers as an input and returns the product of these numbers as an output such that entering

>> product(2,4,6)

displays

ans = 48

## 2.10. Array and Matrix Inputs and Outputs

Use the help for the built-in `sum`

function to determine how to use it so that instead of the columns of `M`

being returned, the sum of the rows are returned. That is, what should be entered for `?`

>> M = [1,2,3,4;1,2,3,4] >> sum(?)

so that

10 10

is returned.

## 2.11. Procedure for Creating a Function

The following program replaces all zeros in an array with ones:

A = [0,-1,0,1,2] for i = [1:5] if (A(i) == 0) A(i) = 1; end end A

Create a function that will allow one to enter:

>> replace0with1([0,-1,0,1,2])

and result in a display of:

ans = 1 -1 1 1 2

Answer |
---|

function A = replace0with1 (A) for i = [1:5] if (A(i) == 0) A(i) = 1; end end When the following is entered: >> replace0with1([0,-1,0,1,2]) this is displayed: ans = 1 -1 1 1 2 |

## 2.12. Procedure for Creating a Function

Create a function that returns a square matrix with a circular shape given one input corresponding to the width of the matrix. The function should be able to create an output matrix of arbitrary width, not just a 16x16 matrix as shown below.

Use the following program, which creates a circular shape in a 16x16 matrix, as a starting point.

for i = [1:16] for j = [1:16] if ( (i - 8)^2 + (j - 8)^2 ) <= 17 M(i,j) = 0; else M(i,j) = 1; end end end

Answer |
---|

In this case, we need to first generalize the example program by identifying all places in the code that depend on the size of the matrix. function M = circleinmatrix(n) nhalf = n/2; for i = [1:n] for j = [1:n] if ((i-nhalf)^2 + (j-nhalf)^2) <= n+1 M(i,j) = 0; else M(i,j) = 1; end end end |

## 2.13. Unusual Behavior

A friend is working on the command line and calls you on the phone for help. When they enter

sin(pi/2)

on the command line, they see

ans = -1

You start a MATLAB session on your computer and enter

sin(pi/2)

and see

ans = 1

You also try this on a few computers in the computer lab and get the same result.

Explain a possible reason why your friend is getting a different answer.

Save your answer in a file named `HW1.txt`

. Create this file (and all .txt files for this class unless otherwise specified) using a text editor such as Notepad or Notepad++ on Windows, TextWrangler on OS X, or GEdit on Linux.

Answer |
---|

The student probably entered function y = sin(x) y = -1; In this case, the re-defined the function |