# Getting to know Matlab

Matlab (the name comes from **MAT**rix **LAB**oratory) is a program that's used by all students here from their first day. At its simplest it's a graphical calculator, but it's a lot more than that. It can be used to write programs that our students use to learn about engineering.
This page uses material from Dr Gee's handout (thanks Andy) so that you can learn about Matlab while using it. Later there are some problems that you might like to solve.

Your instructor will tell you how to start Matlab.

## Numbers and Vectors

Enter the following commands into the Matlab window. You can type them in or copy/paste them. A quick way to copy/paste is to

- copy by dragging over the text in this window with the left button
- paste by clicking in the matlab window with the middle button

a = 5 b = 3 c = a + b

Look at the output. You have just stored the number 5 in the variable `a`, the number 3 in the variable `b`, calculated the sum of
`a` and `b`, and stored the result in the variable `c`. Note how Matlab responds to each command with
the result of the calculation.

Matlab variables need not be scalars (single numbers), they can be vectors (lists) too. If you type

X=1:10

you'll see that X has the integers from 1 to 10 in it. If you want the difference between consecutive numbers to be 0.5 rather than 1, you can type

X=1:0.5:10

X is a row vector. Try typing this

a = [1 2 3 4 5] b = [6; 7; 8; 9; 10] c = a + b;

Note the two different ways of entering column vectors. `a` and `b` can be added together because they're the same shape. Note how the contents of c were not
displayed this time. This is because of the semicolon, which suppresses
output. In general, we write Matlab programs with semicolons, but we can remove
them to see what is going on when debugging. Type

c c(1) c(3) c(1:3)

Here, we have isolated individual elements of the vector c by specifying a
single index inside the brackets. `c(1)` is the 1st number in c.
Note that we can specify a range of elements using a colon. `c(1:3)` is
the 1st 3 numbers in c. Matlab can
also handle matrices. Type the following and look at the output

c = [1 2 3 4 5 6 7 8 9 10] c(2,1) c(:,1) c(:,2) c(1,:) c(5,:) c(1:3,:)

`c(2,1)` refers to the element in the second row and first column of the matrix `c`. A colon without an
upper and lower bound indicates the full range of indices. So, `c(:,1)` refers to all the elements in the first
column of `c`. `c(1:3,:)` refers to all the elements in the first three rows of `c`.

At this point, you might like to experiment with the up and down cursor keys to recall commands you previously entered. You can edit these commands and then hit return to submit the edited command. You can find the size of matrices. Type

d = size(c)

This creates a vector d containing 2 values showing the number of rows and columns.

## Decisions

Type

if d(1) == d(2) disp('c is square') else disp('c is not square') end

(`disp` is short for "display" - it's a command to display things).
This is how to execute commands conditionally. The first message is displayed if c has the same number
of rows as columns, otherwise the second message is displayed. Note the use of == to test equality: this is
different from =, which denotes assignment, as in a = 5. The "else" clause can be
omitted:

if d(1) ~= d(2) disp('d is not square') end

~= tests for inequality. The other possible tests are >, <, >= and <=.

## Repeating

Let's go loopy. Try this

for i=1:100 disp(i) end

This is how to program a fixed length loop. Every command between the `for` and `end` statements is
executed repeatedly while i counts from 1 to 100. In this example, all the program does is display the
current value of i at each iteration of the loop. Check that you understand this by writing a similar loop
that is executed ten times, displaying the numbers 10, 11, 12 . . . 19.

You can have loops inside loops. For example, the following code prints all the integers from 0 to 99

for tens=0:9 for units=0:9 number=10*tens+units; disp(number); end end

Note that some lines have been indented to make the code easier to read. The code works fine without the indentation. Another kind of loop is a "while" loop. The following example
decreases `i` each time, printing it out until it becomes 0.

i=10; while i>0 disp(i) i=i-1; end

## Programs

By now, your fingers are probably aching and you must be wondering whether you really have to type in every Matlab command each time you want to execute it. Happily, the answer is no. You can save programs in files and re-run them whenever you like. Open your Home folder and right-click inside the folder (or use the File menu), select Create Document then Empty File. Call it myprog.m - all Matlab programs must have the suffix .m. Now double click on the new file to open it in an editor. Type the following Matlab program in.

i = 0; tic; while toc < 5 i = i + 1; end disp('Iterations per second') disp(i/5)

Save the file using the File menu. Now return to your Matlab window and type the following.

myprog

You should see the results of your program. `tic` starts a
stopwatch. `toc` tells you how many seconds have passed since the last `tic`. What does the answer tell you?

## Programs and functions written for you

Just as a calculator has functions like `sin` and `sqrt`, matlab
has functions too. If you try

sqrt(9)

you'll get the expected answer. `sqrt` can cope with vectors, so

sqrt(1:9)

works too, giving you the square root of integers from 1 to
9. `sqrt(-1)` works as well. Here are just a few other functions which might be useful to you later

rem(X,5)

- the remainder when X is divided by 5. X can be a single number or a vector. Try doing `X=1:9` then running `rem(X,5)`

length(B)

- the length of B (if B is a scalar, its length will be 1)

floor(X)

- the nearest integer less than or equal to X

randi(n)

- a random integer from 1 to n.

plot(X,Y)

- plot the values in the vectors X and Y as a line-graph. For example

X=0:.1:10; plot(X,sin(X))

plots the values in X against sin(X).

If you want to know more about a Matlab command, use `help`. For
example, to find out how to sum numbers, type `help sum`

## Writing your own functions

You've used Matlab's functions. Now it's time to write your own. Put the following into a file called `roll2dice.m`

function answer=roll2dice answer= randi(6) + randi(6);

It adds 2 random integers between 1 and 6, simulating the rolling of 2
dice. Try typing `roll2dice` in Matlab to run this new function. Try it
a few times to see if it looks random.

## Problems

Try these in any order.

- In the following addition sum each letter represents a digit.
Find the digits that make the sum come out right (you can do it by "brute force", using loops within loops to generate all the possible combinations, checking each one to see if it works). One answer is that all the
digits are 0, but there are other answers too.
THE TEN MEN ---- MEET

- Simulate rolling 2 dice 100 times and display the results. To store 100 results
you could try this idea. It creates an empty vector, adding a number to it each
time it goes round the loop so that in the end it's a vector containing 100 numbers.
results=[] for i=1:100 results=[results roll2dice]; end

You could use Matlab's`hist`function to display the results (type "help hist" to see how to use it). The graph isn't likely to be very smooth. Try rolling the dice 10000 times instead. - Write a function called
`roll10dice`to simulate rolling 10 dice at once and repeat the above experiment using this new function. If you run it 10000 times how many 60s do you get? - Matlab has a command called "magic" that creates magic squares. For
example,
`x=magic(7)`creates a 7 by 7 square whose rows and columns all add up to the same total. Write a program to check that this is so. What is the total? Do the diagonals also have the same sum? - Computers aren't always that good at doing sums. Type in this
4/3 - 1/3 - 1

Now type in this4/3 - 1 - 1/3

The answers aren't quite the same. The difference is small in this case, but the differences can acculumate, as the following example shows. What should the answer to the following be?x=0.2 x=x*11-2

Matlab seems to give the right answer. Use the up-arrow key to run`x=x*11-2`again. Is the answer still ok? Keep running the command. Count how many commands it takes for the answer to be more than a thousand. Coping with this kind of problem in nuclear reactor simulations keeps engineers busy. - 6 players pick a captain by forming a circle then eliminating every n'th person. The last person left will be the captain. The 2nd person in the counting order can choose n. If they want to be captain what's the smallest n they should pick?
- Pick a number. If it's even, divide by 2. If it's odd multiply by 3 and add 1. Continue this until you reach "1". E.g. one sequence could be 3-10-5-16-8-4-2-1. Which integer less than 100 produces the longest chain?
- Pick a number. Multiply the digits together. Continue until you get a single digit. What is the only 2 digit number which would require more than 3 multiplications?
- Minibuses seating 10, 12 and 15 passengers can be used to convey 120 passengers. There are 5 of each size of bus. How many different ways can the buses be used so that all the ones used are full? Which way uses the least buses?
- Find the only Pythagorean triplet, a, b, c, for which a + b + c = 1000 (a Pythagorean triplet is 3 numbers that could be the lengths of the sides of a right-angled triangle)

## Other problems

If you want to try some other problems, hundreds are online. Have a look at

- http://www2.eng.cam.ac.uk/~tpl/maths/puzzles.html
- http://projecteuler.net/index.php?section=problems
- http://www.mathworks.com/moler/exm/chapters.html

## Don't try this at home

There's a free program called "Octave" that works with MacOS and Windows. It doesn't do everything that Matlab can do, but it can do everything that's been mentioned here. Why not give it a go?