



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Learn how to write and use user-defined functions in MATLAB with this comprehensive guide. Discover the syntax, examples, and local variables. Create simple functions and more complex ones like the quadratic formula. Understand the concept of dummy variables and local variables.
What you will learn
Typology: Study notes
1 / 6
This page cannot be seen from the preview
Don't miss anything!
Leigh J. Little SUNY Brockport October 20, 2021
1 Writing Your Own MATLAB Functions 1
2 Syntax for a Function 1
3 Example 1: A very simple function 2
4 Example 2: An Absolute Value Function 3
5 Example 3: Local Variables 3
6 The Quadratic Formula 4
7 A Second Solvequad Example 6
The ability to write your own functions is a critical component to programming, not just in MATLAB, but in any programming language. It makes writing complex programs easier to manage and understand.
The following rules apply when you write your own function in MATLAB.
You must choose a name for your function. This cannot be the same as an existing MATLAB function, some other function that you have written yourself or a variable name you are likely to use in your programs. For example, choosing to name your function n would be a terrible idea because n is commonly used as a variable. For this discussion, we will assume the name of the function is fname
Your function must be saved in a file called fname.m.
Your function must be in your working directory (there are ways around this, but we will use this rule for now).
A MATLAB function has the generic template
function [list of output arguments] = fname(list of input arguments) % % Comments (not required, but recommended) % | | | MATLAB statements to be executed by the function |
Some important items to note:
a) The function starts with the function keyword. This line must be the first line in the file.
b) The list of output arguments is enclosed in square brackets, not parentheses.
c) You can include a comment section at the top (and anywhere else in your function).
d) You can have any number of input arguments, of any type (scalar, vector, matrix, etc.). You can also have a function with no inputs.
e) Item d also applies to output arguments.
f) The ordering of the arguments is important. We will see more on this shortly.
g) This example function would need to be saved in a file called fname.m
Enter the following into the MATLAB editor and save it as fun1.m
function [] = fun1(invalue)
disp(’The value you sent in is ’) invalue
Examine what this function does by executing it several times for different inputs:
fun1(5) The value you sent in is invalue = 5 fun1(-1) The value you sent in is invalue =
fun1([1 2 3 4 5]) The value you sent in is invalue = 1 2 3 4 5 fun1(’Evil Steve’) The value you sent in is invalue = ’Evil Steve’
We can see that this function displays whatever you put between the ( ) along with a message. The values sent as inputs to a function do not have to be static values. They can also be variables:
a = 3; fun1(a) The value you sent in is invalue = 3 x = [5 7 2 -1 4]; fun1(x) The value you sent in is invalue = 5 7 2 -1 4
This is the most critical aspect of functions. The variable invalue that appears in the function is called a dummy variable or dummy argument. Consider the following:
f (x) = x^2 sin (x) f (z) = z^2 sin (z) f (t) = t^2 sin (t) f (blob) = (blob)^2 sin (blob)
Each of these functions is stating the same relationship. All of them say to square the input then multiply that by the sine of the input. In this example, we say that x, z, t and blob are dummy arguments. The
This function takes a value n as input. It then creates a column vector x of all zeros of length n. It then executes a loop that sets each element of x equal to the square of the index variable. Note the index variable i. This variable does not appear in the list of either input variables or output variables. The variable i is called a local variable. A local variable is one that is needed for a function to complete its task, but does not appear in the input or output list of variables. Most importantly, the existence of this variable is unknown outside the body of the function. For example, the command window does not know that i exists. If you look at the workspace panel, the only variable that shows up is ans.
For the quadratic equation ax^2 + bx + c = 0,
you know that there are two solutions (counting multiplicities) and that the formula for these roots is
x =
−b ±
b^2 − 4 ac 2 a
We can easily write a MATLAB function that will compute the roots of a quadratic equation given the values of a, b and c.
Enter the following statements into a file called solvquad.m :
function [x] = solvquad(a,b,c) % [x] = solvquad(a,b,c) % % This function solves the quadratic equation % % a * x^2 + b * x + c = 0 % % for the two roots and returns the result in a % vector of length 2.
x(1) = (-b + sqrt(b^2-4ac)) / (2a); x(2) = (-b - sqrt(b^2-4ac)) / (2a);
This function computes the two roots and stores them in a vector of length 2. x(1) corresponds to the positive root and x(2) corresponds to the negative root.
Notice that we have named the function solvequad. This does not conflict with an existing MATLAB function name, so it is safe to use this name for the function.
Some other items to note:
The user will supply values of a, b and c when they call the function.
When the function is called by the user, the first argument is assumed to be a, the second is assumed to be b and the third is assumed to be c (see example below).
There is a comment section that the top that describes what the function does.
We can immediately start storing the computed roots into the vector x. We don’t need to tell the function that x is a vector.
We can test this function to see if it does what it should by having it compute the roots of a quadratic equation whose roots we know. Consider the equation
x^2 + x − 6 = 0.
For this equation, we know the two roots are x = 2 and x = − 3. Also, the coefficients are a = 1, b = 1 and c = − 6. We can compute the roots of this equation by doing
soln = solvquad(1,1,-6) soln = 2 -
Notice that the function correctly returns 2 and -3 as the roots. Similarly for the equation
x^2 + 9 = 0
we know the two roots are x = 3i and x = − 3 i and that the coefficients are a = 1, b = 0 and c = 9. We can compute the roots of this equation by doing
soln = solvquad(1,0,9) soln = 0.0000 + 3.0000i 0.0000 - 3.0000i
One critical item to note is that even though we named the output variable x in the function body, we can name the output anything we want when we call the solvquad function. In the main workspace, we named the output of the function soln. The is another example of what we mean when we say that the variable names in the function .m file are dummy variables.
To further illustrate this, consider the following example:
hat = 1 cat = 0 football = 9 ratsnest = solvquad(hat,cat,football) ratsnest = 0.0000 + 3.0000i 0.0000 - 3.0000i
This example illustrates two important concepts:
Arguments to functions can be hard-coded numbers (like in the first two examples) or they can be the names of other variables.
We are using the variable names hat, cat and football in the workspace. These are different names than we use in the solvequad.m file. When the function is invoked, the function will use hat as the a variable, cat as the b variable and football as the c variable. This is what makes functions so useful. We can write a process for solving a quadratic equation regardless of the variable names we send in from the main workspace.
For example, the following version of the solvequad.m function would perform exactly the same:
function [cow] = solvquad(orange,apple,banana) % [cow] = solvquad(orange,apple,banana) % % This function solves the quadratic equation % % orange * x^2 + apple * x + banana = 0 % % for the two roots and returns the result in a % vector of length 2.
cow(1) = (-apple + sqrt(apple^2-4orangebanana)) / (2orange); cow(2) = (-apple - sqrt(apple^2-4orangebanana)) / (2orange);
Finally, if you ask for help on the solvquad function, MATLAB will echo the comment section at the top
help solvquad [x] = solvquad(a,b,c)
This function solves the quadratic equation