You are on page 1of 25

Didn’t you say Matlab is a programming language?

I did! Nice to see you were paying attention.

Based on the last lecture, you might think that Matlab is a


particularly fancy calculator. Good for finding eigenvalues, but
nothing your pocket calculator can’t do in a pinch.
Matlab shows its real utility when you start writing your own
scripts and functions.
Scripts and Functions

A script executes a series of commands one after the other. Think


of it as executing a series of command window instructions. Any
variables created will be saved to the workspace, and it can access
any variable currently saved in the workspace.

A function generally takes some inputs, executes a series of


instructions, and returns some outputs. It can only use variables
that are passed in as inputs, and will only return the variables that
are passed as outputs.

Both scripts and functions are saved as .m files. You should make
sure that the .m file is in your working directory (or working path),
otherwise Matlab can’t find it.
Our first script

If we click on the ‘New script’ button, we can write a simple script:

We use the % symbol for commenting. Comment your code


carefully and thoroughly - I cannot stress this enough! It seems
unnecessary now, but developing good coding habits is important.
You’ll thank me later.
If we save and run this code, it saves A, b and x to the workspace.
That was underwhelming

We didn’t really accomplish much beyond what we already know


how to do in the command window. But now we can learn about
flow control.
We’ll learn three flow control statements: if, for, and while.

• if: Check to see if a conditional is satisfied, and if so, do a


thing.
• for: Repeat instructions a prescribed number of times as a
variable changes.
• while: Repeat instructions until a conditional is no longer
satisfied.
If statements
An if statement checks that some condition is satisfied, and
executes commands if this is the case.
If statements

Here Matlab checks to see if the random number X is greater


than 0.5. If it is, the script uses the fprintf command to print
‘Heads!’ in the command window.
If the check fails, the script prints ‘Tails!’ instead.
(Don’t forget to end your if statement!)
Conditionals

Checking an if statement requires a conditional test. Matlab


knows several conditionals:

• < : Less than


• <= : Less than or equal to
• > : Greater than
• >= : Greater than or equal to
• == : Equal to
• ∼= : Not equal to
Conditionals

Matlab allows us to combine conditional expressions using logical


operations:

• & or && : And (both arguments must be true)


• | or ||: Or (at least one argument must be true)
• ∼ : Not (the argument must be false)

For example, if we want to test if a number p is greater than five,


and less than or equal to ten, we could write:

(p > 5) & (p <= 10)

We need to group logical expressions with parenthesis, so Matlab


knows what order to evaluate them.
If statements
We have a little more control than previously advertised:
A final note on if statements

Here Matlab performs two different checks (X , Y > 0.5;


X , Y ≤ 0.5) using the if and elseif statements. If both fail, the
script follows the instructions in the else statement.
For loops
A for loop allows the script to repeat a set of instructions a fixed
number of times:
For loops

A for loop allows the script to repeat a set of instructions,


changing something each time. That change can just be a counter,
or some property of the problem that you want to vary.
The syntax is something like:

It is very important to end your loop. Otherwise you’ll get errors.


For loops

This loops over even numbers (incrementing by two) up to 20, and


finds their sum by adding the new even each time the loop runs. It
also keeps count of how many numbers have been added.
It then finds the average and outputs both quantities to the screen
(note that %d prints an integer, and %f prints a decimal).
For loops

We can nest for loops inside each other:

The outer loop runs across each row, and the inner loop runs down
each column. This allows us to add up every matrix element.
For loops

Loops don’t have to have integer increments, or even regular


increments at all. These are both valid for loops:

The first increments over 1, 1.25, 1.5, ... 4. The second loops over
the elements of the vector.
While loops
While loops combine a loop structure with a conditional. The
syntax is as follows:
While loops

The syntax of a while loop is as follows:


While loops
This while loop looks for the tenth prime number. Each time the
loop runs, it increments the number and tests whether it is prime.
If it is, it adds to a counter. Once the counter reaches ten, the
loop stops.

The number stored as val is the tenth prime number.


While loops: A Warning

While loops are risky!


A for loop will always terminate, but a while loop can run forever if
you aren’t careful.
You need to be very sure that your condition will eventually fail.
It’s often smart to ask yourself if you really need a while loop, or if
a for loop can do the job.

This is all we’ll say about flow control, but there are other options,
including switch, break, and return. Feel free to explore these if
you are interested.
Some final notes on scripts

Using flow control lets you write much more sophisticated scripts.
You can run a script from the command window by typing its
name (without the .mat).
Well-written code is properly indented. Matlab generally does
this for you, by adding an indentation every time you start a new
loop or conditional. This helps you keep track of what is going on.
The problem with scripts is that if we want to change something,
we have to load the script, make the adjustment, and run it all
again. If only there was a way we could change values on the go...
Creating functions

Functions allow us to do just that! A function takes some number


of inputs, and produces some number of outputs. Nothing gets
saved to the workspace, which keeps it from getting cluttered, if
you care about that sort of thing (you should).

The template for a function should look something like this:


function [ outputs ] = functionname( inputs )
Stuff goes here
end
This should be saved as functionname.m, so that Matlab can
find the correct function when you call it.
Creating functions

This function takes two numbers as input, and returns their


geometric mean and the sum of their squares:

We then save the function as geometricmean.m.


Creating functions

To use this function, you would type the following line in a script
or the command window:

This saves the geometric mean as X and the sum of squares as Y .


Creating functions

The commented section at the beginning of the function wasn’t


just for show:

You should make sure this section includes a description of what


your function does, and a list of all inputs and outputs.
Final notes on functions

Functions can also contain loops and conditional statements.


If you don’t need every output of a function, use ∼:

[X, ∼] = geometricmean(A, B)

Functions are incredibly versatile, and it’s generally good practice


to use them whenever possible. Scripts seem like they’re easier,
but functions keep variables and workspaces under control.

You might also like