You are on page 1of 42

 THE BASICS

o WHAT IS PROGRAMMING?
o COMMAND PROMPT AND EXPRESSIONS
o LISTS, VECTORS, AND MATRICES
o VARIABLES
 ROOT-FINDING
o WARM-UP
o NEWTON'S METHOD
o THE SECANT METHOD
o MORE SUB-INDEXING
 BASIC PLOTTING
o WARM-UP
o BASINS OF ATTRACTION
 VECTORIZATION
o WARM-UP
o COMPLEX NUMBERS
o USER-DEFINED FUNCTIONS
o SCOPE
 FRACTALS AND CHAOS
o LOGISTIC EQUATION
o MORE ON LOOPS
o TERMINATING A LOOP PREMATURELY: BREAK AND CONTINUE
o TRUTH STATEMENTS AND LOGICAL INDEXING
 DEBUGGING WITH MATLAB
 CONWAY GAME OF LIFE
o WARM-UP
o CONWAY GAME OF LIFE IMPLEMENTATION
 LIBRARY
o MORE PROJECTS
o VIDEOS
 Every computer is a machine. It does not think. It cannot understand. It does not
know what you want it to do.
 Everything you want it to do must be told to it, explicitly in its language. In this
course we are discussing the MATLAB® syntax.
 When you run MATLAB for the first time, you will see a screen that has various
parts. The important one for now is the "Command Window." To close all the
others, open the "Desktop" menu and unselect all selected options, except for
"Command Window." You should have now, a single frame, which is white, expect
for ">>" and, perhaps a blinking cursor.

Command Prompt and Expressions

At its heart, MATLAB® is a big calculator. To calculate something simply


type it in at the "command prompt" and press Enter. Thus, to calculate 1
+ 1 we type it in and press Enter. The screen should show:
>> 1+1 ans = 2

meaning that the answer is 2.

Exercise 1. Run MATLAB, find the command window and the blinking
cursor. Find the answer to the following arithmetic problems:
 1234+4321=?
 104−765=?
 47∗33=?
 34=? (The operator for "power" is the circumflex ^, usually found by pressing Shift
⇑6
 How far is 192 from its approximation 202−2∗20 (Remember
that (a−b)2=a2−2ab+b2, thus the answer should be ±1)
 Find an approximation to 1/73
 Find an approximation to 31 (while you can of course use the fact that x=x0.5, you
can also "look for" a dedicated function square root by learning how to use
thelookfor command....)
 If you get 5% interest-rate (yearly) on a loan, compounded monthly, and you start
with $1000, how much money will you have after 20 years? (don't be confused by an
answer of the form 2.7e3 which simply means 2.7×103)
 If two sides of a right triangle have lengths 31 and 45, what is the length of the
hypotenuse?

You may have noticed in the exercises that the answer is only given with 5 digits of
accuracy (at most). For example, we can ask MATLAB for the value of π and get:

>> pi
ans =
3.1416

Internally, MATLAB keeps a 16 (more-or-less) digit version of the number it shows us, but
to keep things orderly, it only displays the answer rounded to show 5 digits (by default).
We can change this by issuing a command:

>> format long


>> pi
ans =
3.141592653589793

We can see this, by subtracting part of π from ans, which always holds the full, unrounded
answer to the previous, unassigned expression:

>> format short


>> pi
ans =
3.1416
>> ans-3.1415
ans =
9.2654e-05
>> ans - 9.2653e-5
ans =
5.8979e-10

Exercise 2. Remember the cosine rule? c2=a2+b2−2abcos⁡(θ). Find the length of the
hypotenuse of a triangle with angle 30ο, and sides with lengths 10 and 20.
TheMATLAB trigonometric functions (cos, sin, tan) use radians, so you will need to
convert using π.

For guided practice and further exploration of how to use the command prompt,
watch Video Lecture 2: The Command Prompt.

Lists…..

MATLAB® is particularly convenient at calculating with lists of numbers.


In fact, it was built for manipulating two-dimensional lists called matrices.
An n-by-m matrix has n rows and m columns of numbers, and many
MATLAB commands know how to work correctly and efficiently with
them.
For example, if we have 10 grocery items whose price we would like to
add up, we can write
>> sum([2.35 3.45 10.55 12.32 1.99 5.43 2.66
3.78 10.21]) ans = 52.7400
Here we used a function sum and its argument was a (row) vector we created "manually".
Other vectors have shorthand notation (try them out with various numbers):
 Many zeros: zeros(n,m) (n and m must be positive integers)
 Many ones: ones(n,m) (same)
 An increasing list (step =1): n:m (m must be greater than n)
 An increasing list with step-size s: n:s:m (m might not be the last element of the list)
 A column vector (manual): [3 ; 2; 6 ; 7] (notice the semicolons)
 A column of increasing numbers (using transpose) (n:m)'
Exercise 3.
Do the following practice exercises:
 Try out sequences with step-size ≠1: [4:0.1:5], [5:-2:-5].
 Create a list of the whole numbers between 10 and 20 (inclusive), find their sum.
 Create the vector of the previous question in decreasing order.
 Find the sum of the odd numbers between 100 and 200.

Variables

Often, a result of some calculation is needed for later use, or perhaps a


complicated expression can be examined more carefully if done in parts. Both
can be done by the use of "variables". Variables hold whatever result you put in
them by the use of the equal sign (=):

 x=1 creates a variable called "x" and stores the value "1" in it. If one then
types "x" in an expression, MATLAB® will use the value stored in "x", i.e.,
"1".
 Similarly one can define variables to hold anything that MATLAB can calculate.
 You can easily overwrite a variable with a new assignment: x=2 now the variable x
"contains" the value "2".
 One can use x as part of an expression: x^2+x-cos(x)
 Or to create a new variable: y= x^2+7
 A variable can be a vector (or matrix): A= [1 2 3 4]
 One can change just a part of A: A(3)= 0

In this last example, we are getting ahead of ourselves by referring to an element of a


vector. We will touch on that more later.

Note that you can "hide" important MATLAB functions and constants by defining a
variable with the same name:pi=3 will give interesting results later (to remove clear pi).
This is usually not a good idea, so take care before using a nice name like sum, exp, or det,
as these are all built-in functions. You can check if a variable is already in use by using
the which command:

>> which pi built-in


(/Applications/MATLAB_R2011b.app/toolbox/MATLAB/elmat/pi)

tells us that pi is a built-in function, while

>> which Pi 'Pi' not found.

tells us that Pi is unused. The difference is in the capitalization. MATLAB-defined


functions will always use lower-case names (even if the helpfile will show these as all
CAPITAL), which implies that you can always avoid collision by capitalizing the fiirst
letter of your variable and functions names.
Homework 1

1. Let x=1 and y=2. Exchange the values of these two variables without specifically using '1'
or '2' i.e., the exchange should work regardless of the values held by the variables. Hint:
You can invent a new variable. Another Hint: Imagine you have misplaced your kids'
breakfast and now Tom's Cornflakes are in Sally's bowl and Sally's CocoPuffs are in Tom's
bowl. You have already poured the milk, how can you fix the problem without throwing
away and starting over?
2. Repeat some of the previous exercises using variables.

Root-Finding

MATLAB can calculate roots through Newton's method, and verification of


convergence is graphed.

Now that you are familiar with MATLAB® and its basic functionalities, you
will learn how to use MATLAB to find the roots of equations, and
specifically, nonlinear equations. We will walk through using Newton's
method for this process, and step through multiple iterations of Newton’s
method in order to arrive at a final solution.

Because Newton's method is an iterative process, you will also learn how
to construct two types of logical loops:for loops and while loops. These
loops will be useful tools not just for the purpose of using Newton's
method, but also for future use in writing code that can handle more
complicated operations. In addition to learning how to construct loops,
you will be introduced to plotting in MATLAB and saving code in a file for
future or frequent use.

The secant method is presented as an alternative to Newton's method, and you will be asked
to use MATLAB in comparing the convergence of solutions—essentially, the speed at
which they can approximate a solution—from these respective methods. When completing
this portion of the unit, you will find the need to store multiple values for comparison, and
this offers the opportunity to make use of lists and sublists through sub-indexing. Since
discrepancies in syntax are important when it comes to using and operating on lists and
matrices in MATLAB, you will be asked to evaluate a variety of expressions that help you
understand these differences.

Related Videos

The videos below demonstrate, step-by-step, how to work with MATLAB in relation to the
topics covered in this unit.

 Lecture 3: Using Files


This video includes material supplementary to The Secant Method.
 Lecture 6: Debugging
This video includes material supplementary to The Secant Method.

Warm-up

Here are some warm-up problems:

 Create the list of numbers from 3 to 10


 Create the list of even numbers from –20 to 20
 Create the decreasing list of numbers from 100 to 90

Remember variables? There's one variable that is special:


The ans variable holds the last calculated value that was not placed into a
variable. This is nice when a command you give MATLAB® returns a
value that you realize is important, but forgot to assign into a variable:
>> sin(pi/2) ans = 1 %%oops! I meant to save the "return value" in
the variable x >> x=ans x = 1 >>

Now x holds the answer, 1. Of course you could also re-issue the command with an
assignment, but commands can take long to run, and there may be other reasons why you
do not want to re-issue the command.
The secant MTHD

While Newton's method is fast, it has a big downside: you need to know
the derivative of f in order to use it. In many "real-life" applications, this
can be a show-stopper as the functional form of the derivative is not
known. A natural way to resolve this would be to estimate the derivative
using
for ϵ≪1. The secant method uses the previous iteration to do something similar.
It approximates the derivative using the previous approximation. As a result it converges a
little slower (than Newton's method) to the solution:
Since we need to remember both the current approximation and the previous one, we can
no longer have such a simple code as that for Newton's method. At this point you are
probably asking yourself why we are not saving our code into a file, and it is exactly what
we will now learn how to do.

Coding in a File
Instead of writing all your commands at the command prompt, you can type a list of
commands in a file, save it and then have MATLAB® "execute" all of the commands as if
you had typed them into the command prompt. This is useful when you have more than
very few lines to write because inevitably you are bound to make a small mistake every
time you write more than 5 lines of code. By putting the commands in a file you can correct
your mistakes without introducing new ones (hopefully). It also makes it possible to
"debug" your code, something we will learn later.
For guided practice and further exploration of how to debug, watch Video Lecture 6:
Debugging.
MATLAB files have names that end with .m, and the name itself must comprise only
letters and numbers with no spaces. The first character must be a letter, not a number. Open
a new file by clicking on the white new-file icon in the top left of the window, or select
from the menu File→New→Script. Copy the Newton method code for tanh⁡(x)=x/3 into it.
Save it and give it a name (NewtonTanh.m for example). Now on the command prompt you
"run" the file by typing the name (without the .m) and pressing Enter .
A few points to look out for:
 You can store your files wherever you want, but they have to be in MATLAB's "search path"
(or in the current directory). To add the directory you want to the path select File→Set path…
select "Add Folder", select the folder you want, click "OK" then "Save". To check if your file is
in the path you can type which NewtonTanh and the result should be the path to your
file.
 If you choose a file-name that is already the name of a MATLAB command, you will effectively
"hide'' that command as MATLAB will use your file instead. Thus, before using a nice name
like sum, or find, or exp, check, use which to see if it already defined.
 The same warning (as the previous item) applies to variable names, a variable will "hide" any
file or command with the same name.
 If you get strange errors when you try to run your file, make sure that there are no spaces or
other non-letters in your filename, and that the file is in the path.
 Remember that after you make changes to your file, you need to save it so that MATLAB will
be aware of the changes you made.
For guided practice and further exploration of how to use MATLAB files, watch Video
Lecture 3: Using Files.
Exercise 7. Save the file as SecantTanh.m and modify the code so that it implements the
Secant Method. You should increase the number of iterations because the Secant Method
doesn't converge as quickly as Newton's method.
Notice that here it is not enough to use x like in the Newton's method, since you also need
to remember the previous approximation xn−1. Hint: Use another variable (perhaps
called PrevX).
Convergence
Different root-finding algorithms are compared by the speed at which the approximate
solution converges (i.e., gets closer) to the true solution. An iterative method xn+1=g(xn) is
defined as having p−th order convergence if for a sequence xn where limn→∞xn=α exists then
Newton's method has (generally) second-order convergence, so in Eq. (3) we would
have p=2, but it converges so quickly that it can be difficult to see the convergence (there
are not enough terms in the sequence). The secant method has a order of convergence
between 1 and 2. To discover it we need to modify the code so that it remembers all the
approximations.
The following code, is Newton's method but it remembers all the iterations in the list x. We
use x(1) for x1 and similarly x(n) for xn:
x(1)=2; % This is our first guess, put
into the first element of xfor n=1:5 % we
will iterate 5 times using n to indicate
the current
% valid approximation
x(n+1)=x(n)-(tanh(x(n))-
x(n)/3)/(sech(x(n))^2-1/3); %here we
%
calculate the next approximation and
% put the
result into the next position
% in x.end
x % sole purpose of this line is to show
the values in x.
The semicolon (;) at the end of line 4 tells MATLAB not to display the value of x after the
assignment (also in line 1. Without the lonely x on line 9 the code would calculate x, but
not show us anything.
After running this code, x holds the 6 approximations (including our initial guess) with the
last one being the most accurate approximation we have:
x =
2.0000 3.1320 2.9853 2.9847
2.9847 2.9847
Notice that there is a small but non-zero distance between x(5) and x(6):

>> x(6)-x(5)
ans =
4.4409e-16
This distance is as small as we can hope it to be in this case.
We can try to verify that we have second order convergence by calculating the sequence
defined in Eq. (3). To do that we need to learn more about different options for accessing
the elements of a list like x. We have already seen how to access a specific element; for
example to access the 3rd element we write x(3). MATLAB can access a sublist by
giving it a list of indexes instead of a single number:
>> x([1 2 3])
ans =
2.0000 3.1320 2.9853
We can use the colon notation here too:

x(2:4)
ans =
3.1320 2.9853 2.9847
Another thing we can do is perform element-wise operations on all the items in the list at
once. In the lines of code below, the commands preceding the plot command are executed
to help you understand how the plot is generated:
>> x(1:3).^2
ans =
4.0000 9.8095 8.9118
>> x(1:3)*2
ans =
4.0000 6.2640 5.9705
>> x(1:3)-x(6)
ans =
-0.9847 0.1473 0.0006
>> x(2:4)./(x(1:3).^2)
ans =
0.4002 0.0018 0.0387
>> plot(log(abs(x(1:end-2)-
x(end))),log(abs(x(2:end-1)-x(end))),'.'))
The last line makes the following plot (except for the green line, which is y=2x):

MATLAB can calculate roots through Newton's method, and verification of


convergence is graphed.
The main point here is that the points are more or less on the line y=2x, which makes sense:
Taking the logarithm of the sequence in (3) leads to
for n≫1, which means that the points (log⁡|xn−α|,log⁡|xn+1−α|) will converge to a line with
slope p.
The periods in front of *, /, and ^ are needed (as in the code above) when the operation
can have a linear algebra connotation, but what is requested is an element-by-element
operation. Since matrices can be multiplied and divided by each other in a way that is not
element-by-element, we use the point-wise version of them when we are not interested in
the linear algebra operation.
Exercise 8. Internalize the differences between the point-wise and regular versions of the
operators by examining the results of the following expressions that use the
variables A=[1 2; 3 4], B=[1 0; 0 2], and C=[3;4]. Note: some commands
may result in an error message. Understand what the error is and why it was given.
 A*B vs. A.*B vs. B.*A vs. B*A
 2*A vs. 2.*A
 A^2 vs. A*A vs. A.*A vs. A.^2 vs. 2.^A vs. A^A vs. 2^A. The last one here might be
difficult to understand…it is matrix exponentiation.
 A/B vs. A\B vs. A./B vs. A.\B
 A*C vs. A*C' vs. C*A vs. C'*A
 A\C vs. A\C' vs. C/A vs. C'/A
Homework 2. Modify your secant method code so that it remembers the iterations
(perhaps save it in a new file?). Now plot the points that, according to (4) should be on a
line with slope p. What is p?

More subindixing

We have seen how one can access a subset of a list by providing a list of
desired positions:
>> A=rand(1,5) A = 0.6430 0.5461 0.5027 0.0478
0.2289 >> A([2 3 1 1]) ans = 0.5461 0.5027
0.6430 0.6430
There are a few more extensions of this:
It can be used to modify part of a matrix:

%with A as before:
>> A([1 2])=3+A([3 4])
A =
3.5027 3.0478 0.5027 0.0478
0.2289
%or even:
>> A([3 4])=1
A =
3.5027 3.0478 1.0000 1.0000
0.2289
Additionally, this works for matrices and submatrices as well:

>> A=magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
>> A([2 3], [1 4])
ans =
5 8
9 12
>> A(1:2,3:4)=1
A =
16 2 1 1
5 11 1 1
9 7 6 12
4 14 15 1
The keyword end will evaluate to the size of the dimension of the matrix in which it is
located:
>> A=magic(4);
>> A(end,end)
ans =
1
>> A([1 end],[1 end])
ans =
16 13
4 1
>> A([1 end/2], [2, end-1])
ans =
2 3
11 10
>> A(2,1:end)
ans =
5 11 10 8
>> A(1:end,3)
ans =
3
10
6
15
% 1:end is so useful that it has an even
shorter notation, :
>> A(:,1)
ans =
16
5
9
4
>> A(4,:)
ans =
4 14 15 1
Finally, a matrix can be accessed with a single index (as opposed to with two) and this
implies a specific ordering of the elements (rows first, then columns):

>> A(5)
ans =
2
>> A(4:10)
ans =
4 2 11 7 14 3 10
>> A(:)
ans =
16
5
4
2
11
7
14
3
10
6
15
13
8
12
1
Exercise 9: Practice some of these methods for accessing matrix elements with the
following exercises:
 Create a matrix of size N×N that has ones in the border and zeros inside. For example
if N=3 the matrix can be created with
 >> A=ones(3,3); A(2,2)=0
 A =
 1 1 1
 1 0 1
 1 1 1
Make this construction depend on N and work for any positive integer N≥2
 Create a 5x5 matrix whose rows are (1:5)
 Extract the diagonal of a given matrix without using diag (you may use size)
 Flip a given matrix horiztonally. Vertically? Do not use fliplr or flipud
 Extract the anti-diagonal of a given matrix
 Extract the anti-diagonal, without first flipping it (Hint: use single index access)
Need help getting started?

Basic Plotting
MATLAB can graph both functions and non-functions, as demonstrated by
the circle and Lissajous curves.

In the previous unit, plotting was introduced with Newton's method, but
it is worthwhile to further explore the capabilities of plotting in MATLAB®.
Preliminary exercises will encourage you to discover how to stylize your
plots as well as plot multiple functions with the same plot command. To
do this, you will be asked to plot different basins of attraction, sets of
points that converge to a given root, for Newton's method. We will
generalize Newton's method to higher dimensions by writing the function
as a vector and finding the Jacobian matrix, which represents the linear
approximation of the function. To visualize the basin of attraction, we will
color a grid of points according to each point's resultant root after
iterating with Newton's method.

Related Video

The video below demonstrates, step-by-step, how to work with MATLAB


in relevance to the topics covered in this unit.

 Lecture 4: Basic Plotting

Warm-up

 What do 1:10, 1:2:10 100:-25:0 do? Think, then check.


 Let x = [2 5 1 6]. What will x(3), x([1 2]), x([1:end]), x(end:-
1:1), x(:), x([1 1 1 1])do? Think, guess, discuss with a friend, and finally,
verify.
 When creating a matrix, a space or a comma (,) are the separator between columns,
while a semicolon (;) separate between rows. Figure out how to create the
following matrices: (123456), (101010)
 You can nest matrix construction so that [ 6 (1:5) 7 ] makes sense (what does it
result in?) Similarly you can create a matrix by stacking column vectors next to
each other (using a space or a comma) or row vectors on top of each other (using a
semicolon). Create the following matrix using a relatively short line of code:

(1)(123456789101491625364964811002481632641282565121024)

Can you now easily make the first list go up to 100 (and the others follow suit)? If
not, solve the problem again so that you can do it.
The plot command plots a list of points given as two vectors, X and Y of their x- and y-
coordinates, respectively. The default behaviour is that no mark is placed on the points, and
the points are joined by a straight line. So if we want to plot a
parabola y=x2 for x∈[−1,1] we can write:

x=-1:.1:1; y=x.^2; plot(x,y)

Graphing a simple function, y=x^2.

We could make that line green by adding a third input:

x=-1:.1:1; y=x.^2; plot(x,y,'g.')

Stylizing the graphs with colors and line markers.

The resulting plot need not be a function in the mathematical sense of the word:

t=-1:.01:2*pi; x=sin(5*t); y=cos(3*t);


plot(x,y,'r')

Graphing a non-function in
MATLAB®.

Exercise 10. Read the helpfile on plot by typing help plot and figure out how to do the
following:

 Plot only the points and not the lines


 Plot the parabola sideways (the result is not a function)
 Plot using a red, dashed line and stars at each point
 Make the plot with less points so that you can see that the lines between the points
are straight
 Plot the function sin⁡x vs. x, for x∈[0,6π]
 Figure out how to plot two functions with the same plot command, and
plot sin⁡x and cos⁡x vs. x.

Basins of Attraction

Back to Newton's method: It turns out that the end result (the point to
which the method converges, if any) is strongly dependent on the initial
guess. Furthermore, the dependence on the first guess can be rather
surprising. The set of points that converge to a given root is called
the basin of attraction of that root (for the iteration under discussion). I
would like us to visualize the basins of attraction by coloring each starting
point with a color that corresponds to the root it converges to. The
different basins will thus be given different colors.

With MATLAB® we can easily visualize which solution is chosen as a function of the
initial guess. While this can be done for 1D, we will do it for 2D and learn how to do some
simple linear algebra at the same time.

Generalizing Newton's method for higher dimensions is actually quite straightforward:


Instead of one function f, we have many, written as a vector f→, and instead of one
independent variable (x) we have many, again, written as a vector, x→. Thus we are
looking for the vector x for which:

(1)f→(x→)=0→

The update rule is slightly different since derivatives are more complicated in higher
dimensions:

(2)x→n+1=x→n−(Jf→)−1f→(x→n).

Here Jf is the Jacobian matrix of f→, that is a matrix whose term in the i−th row and j−th
column is

(3)(Jf→)ij=∂fi∂xj.

Notice that the Jacobian depends on x→ and thus needs to be re-evaluated at every step
(just like the derivative in one-dimensional Newton's method). The two parts in the right-
most term of (2) are multiplied together in the linear algebra sense of the word. The
power −1 is matrix inverse (and not multiplicative inverse) and thus another way of writing
the update rule is

(4)(Jf→)δx→n=(Jf→)(x→n+1−x→n)=−f→(x→n).

This formulation is a much better way of understanding Newton's method, as it exposes


what is going on: The approximation is updated so that if the linear approximation
to f→ (given by the Jacobian matrix) were exact, the approximation would equal the exact
root in one step.

How to implement? First we need a specific function: f→([x,y]t)=[x3−y,y3−x]t and thus


the Jacobian matrix is(3x2−1−13y2). In MATLAB we want to have one variable, say X, be
a column vector that holds both x and y. The code for a simple Newton method for f would
be:

X=[1;2]; % the starting point. Notice the use of semicolon to define a


column vector for j=1:10 % iterate 10 times
% let's do this using variables so that we can see what's
going on: f=[X(1)^3 - X(2), X(2)^3 - X(1)]'; % Another way to define
a % column vector is to define a
row % vector and then transpose
it using % the apostrophe '.
WARNING the [ ] % is a prime
example of how matlab % can try
to be too smart: look at % the
difference between % [1+2,3]
% [1 +2,3] and % [1 + 2 , 3] all
legal % expressions, but one
gives an % unexpected answer
since we can use % space instead
of comma to separate % terms in a
row vector. Jf=[3*X(1)^2, -1; -1, 3*X(2)^2]; % the Jacobian matrix.
Notice the % semicolon after the
second % term. This is like
saying "now % start a new row".
X=X-Jf\f; % the update rule. This does not invert the %
matrix. By using "left divide" the linear system is solved,
% this is equivalent but faster than inverting and multiplyingend format
long % to see the full precisionX % so that we see the final
answer format short % to only see 4 digits again

Exercise 11. Multi-dimensional Newton's method

 What are the 3 roots of f→ in the code above? (think of them as r1, r2, r3.)
 Implement the program above and play around with the starting point to get several
different answers. If you get a warning about singular matrices, don't worry about
it.
 Find the Jacobian matrix, Jg→, of:

g→(x→)=(sin⁡(x1+2x22)−x2x12x2−x1)

 The function g has many roots; modify the Newton solver to find some them by
manually starting at different places.
 Are you iterating enough times? Check that the results you get are a good enough
root, and if they are not, change the number of iterations so that they are.

Now here's the run-up to the next project: We want to plot the "basin of attraction" of each
of the three zeros (what are they?) of the function f→ (not g→). This will be your first
project, but first we need to discuss how to plot the result. For an initial point X0 we can
run the Newton code and after several iterations (10 in the example above) it will
arrive near (in most cases) one of three roots, say r1,r2,r3. To visualize the basin of
attraction, we go over a grid of points X0 and color them according to the to the specific
zero the Newton's method algorithm ends up being close to after starting from X0. If the
algorithm is not close to any of them, we put a fourth color. While it is true that normally
we do not know what the zeros are, but this is also interesting in the case that we do know
what they are, so we are using the a priori information about the location of the roots in
order to visualize the basin of attraction.

To do this we need if-else-end statements:

if norm(X-r1)<1e-8 % if the distance between X and r1 is less than 10^-8


c='r'; % use the color red elseif norm(X-r2)<1e-8 c='b';
% use the color blue elseif norm(X-r3)<1e-8 c='g'; % use the
color green else % if not close to any of the roots
c='k'; % use the color black end plot(x,y,'.','color',c); % plot a
point at X_0, (not the final point X!) % with
the color c

Project 1. Place the Newton code, and the if-then-else code above inside two
nested for loops, looping overx− values and y− values from -2 to 2 (perhaps with a small
step-size of 0.1 or 0.01). For each iteration set the starting point to [x,y]' before the
Newton's Method part, and then plot the color point corresponding to the location of the
resulting zero. So that the subsequent plot commands do not erase the previous ones, put:

clf % clear the current Figure hold on % make sure subsequent plots
do not erase the previous ones.

before the for loops. Thus the pseudo-code for this construction is:

initialize figure for x values for y values let X0=(x,y)


be the starting point for Newton's method find the color
corresponding to the final point of iteration X plot point X0
with correct color end loop y end loop x

If this is your first programming project, you might get frustrated at how difficult it seems
to get everything in place. There's no way around it. Read you own code carefully. Give
good names to your variables. Try to explain the code to someone else.

That said, there are several hints I can give:

Hint If MATLAB is stuck, use Ctrl C to abort from a long calculation or to reset the
1. command line.
If MATLAB is spewing out too much onto the screen and you cannot see what you
Hint
want to see, add semi-colons (;) to the end of the "offending" lines to prevent
2.
MATLAB from doing that.
Hint If all the points seem to be plotted at the roots rather than at the original points, you
3. are probably using X to do the plotting rather than the original point (x,y) from the
loop.
If you are getting warnings from MATLAB that your "Matrix is close to singular or
badly scaled" don't worry about it too much. It means that your algorithm has passed
Hint
through a point where the Jacobian matrix is singular. The result from that point is
4.
unreliable, but there should be (relatively) few of these points, and so the overall
picture will be preserved.
If you always only have one point on your plot, you are probably not holding the plot
Hint
properly. The two lines of code under the description of the project should be before
5.
the for loops (and not anywhere else).
What is the solution supposed to look like? My result can be seen in Fig. 1. Increasing
Hint
the number of iterations should make the black regions (places that have not
6.
converged) smaller.

Figure 1. Basin of attraction for f([x,y]t)=(x3−y,y3−x)t.

Vectorization and User-Defined Functions


Screenshot of a function definition to convert Fahrenheit to Celsius and
the respective function call.

Another convenience of MATLAB® is its ability to manipulate complex


numbers, such that you can take powers and roots of any number. For
practice, you will be asked to calculate and plot the basins of attraction
for a polynomial in the complex plane.

Also in this unit, you will learn how to create a user-defined function in
MATLAB. It is important to understand the difference between a script
and a function. While a script is a separate piece of code that performs a
certain task, it deals with the variables from the caller, and cannot accept
input values or provide return values. Functions, on the other hand, can
receive an input and deliver an output, and the variables contained
therein are isolated from those of the caller. In determining whether a
script or function should be used, you will need to consider the scope of
the variable. Within a function, variables exist within that small space of
code, and values changed within the lines of code in the function will not
affect those outside in the calling workspace.

With this knowledge, your first task will be to write a function that
calculates the Fibonacci numbers. This function will be recursive, meaning
that it calls itself, because each Fibonacci number is calculated by taking
the sum of the previous two Fibonacci numbers in the sequence.
As an exercise, you will be given a piece of code that calculates and plots
the solution to the Van-der-Pol oscillator. You will also be given a series
of tasks by which to edit the code and resulting plot, and later, to debug
the code.

Related Videos

The videos below demonstrate, step-by-step, how to work with MATLAB


in relevance to the topics covered in this unit.

 Lecture 5: Scripts and Functions


This video includes material supplementary to Scope.
 Lecture 6: Debugging
This video includes material supplementary to Scope, Homework 3.

Vectorization and User-Defined Functions

Code an arbitrary precision (integer) addition code. The start of the code
should be where the "numbers" are defined. For example:
N1=[1 9 5 4 3 8 4 8 5 6 0 3 4 0 5 3 2 4 5 6 ]; % to mean
19543848560340532456 N2=[2 3 4 3 2 3 4 5 4 8 6 4 7 8 9 7 6 5 3 2 1 4 6 7
9 ]; % stands for 2343234548647897653214679

These numbers are to big to be represented exactly in MATLAB®. Your task is to write
code that follows the rules of addition (adding from smallest to largest) and gets the precise
answer, in the same format (that is an array of integers). There are various limitations that
need to be discussed:

 First try doing this while allowing yourself only to add small 20 numbers using
MATLAB +. You will still need to be crafty about how you find the "ones'' and
"tens'' of a given number. Since MATLAB is good with lists, think how you can use
a list to do this. You may not use high level functions like mod, rem etc. (But you
are encouraged to familiarize yourself with them.)
 Can you do it with a matrix that represents the addition table for numbers between 0
and 11? Once you create this matrix, you can solve this exercise with +1 as the only
"allowed'' arithmetic operation (because MATLAB's index of lists starts from 1 and
not 0).
 Redo this exercise for a different definition of addition, for example, for Z16.

Complex Numbers
Complex numbers x+iy can be dealt with "natively" in MATLAB®. This
means that you can take powers and roots of any number. One surprising
and very powerful fact about complex functions is that a single derivative
(not a 2×2Jacobian) gives you the full derivative information (assuming
that the function is analytic).

Exercise 12: Modify your 1D Newton's method to find the basins of attraction of a
interesting (degree > 3) polynomial. Plot the basin of attraction as before, but now you will
have to create your initial value by z=x+iy. For the roots: either use a polynomial for
which you know the roots, or find the roots in advance, by using your own Newton solver.

Here's the basin of attraction of the roots of z5+1:

A plot of the basin of attraction with complex roots.

How long does it take your code to make a 1000 by 1000 plot (that is, a plot in which both
the x- and y-axes have 1000 points)? If it's more than 1 minute, your code is too slow. The
reason for that is that MATLAB can be inefficient with explicit loops. In this case, we have
nested loops and a plot command inside them; this is a disaster!

We need to "vectorize" the calculation and only plot once at the end after we have the
result. This means instead of having MATLAB loop over the points and calculating each
one at a time, you set them all up in a big matrix/vector and iterate on all of them together:

We let a matrix A hold all the values of the iterations that correspond to the different points
we will end up plotting. Thus we can set up the initial A as follows:

N=1000; x=linspace(-5,5,N);% linspace is another function that creates


vectors. y=linspace(-5,5,N); % Read about it! A=ones(N,1)*x +
1i*y'*ones(1,N); %A is a 1000x1000 matrix. % Notice the use of linear
algebra to create a matrix out of two vectors. % Make sure you understand
this.

Exercise 13. Make sure you understand:

 What does ones do? Find out using help ones


 Can you guess what zeros does?
 We can also use meshgrid for this, can you understand how to do it?

In the one-at-a-time Newton's method the update step is

(1)xn+1=xn−f(x)f′(x)

We want to do the same only updating all of A at every step. It would work just fine if we
could write

A=A-f(A)./f'(A); %Notice the ./ ? This means, POINT-WISE multiplication,


% not linear algebra

And we can. We only need to make sure that we define functions f and f′ that know how to
work with a matrix and return the right answer. We can also make our code more flexible
by using our own functions (f(x) and f′(x)). Here is how to define simple (one command)
functions:

f=@(x) x.^5+1; %Notice the point here? However there's no such thing as
.+ fp=@(x) 5*x.^4; %Here too, but not with the * since the "5" is a
"scalar"

After defining f and fp, they can be used like any other MATLAB function:

>> f(1) ans = 2 >> f([1 2 3]) ans = 2 33 244 >> f([1 2; 3
4]) ans = 2 33 244 1025

Last, but not least, plotting a 2D surface (the following code has nothing to do with our
problem, but it illustrates how to plot a nice 2D surface):

x=linspace(0,2*pi); y=x'; [X,Y]=meshgrid(x,y);%x,y are vectors,X,Y are


matrices Z=sin(X).*cos(Y.^2); pcolor(X,Y,Z);%create a "surface" colored
by Z.

There are slight variations to pcolor: mesh, surf, and more. Learn about them using
the help command.

Project 2. Update your Newton's basin of attraction code to work using matrix-at-a-time
update. Use pcolor to create the resulting basin plot. Your result should be much faster.

User-Defined Functions
We have just seen—above, using the @(x) notation—an example of how
to create simple user-defined functions. This notation can only have one
line of code, and oftentimes that can be insufficient for the task at hand.
We have also seen scripts files, in which we can put many lines of code
and then "call" the script to have MATLAB® execute the lines in that
script. So what's a function and how is it different from a script?

A function is also a file with lines of code, but there are several distinctions between a
function and a script:

Script function difference.

SCRIPT FUNCTION

Interacts with variables from the caller Has very restricted interaction with the caller

Cannot accept input Can accept input

Cannot return a value Can return a value

Can overwrite variables by mistake No need to worry, variables are "local"

Cannot have "sub-functions" in file May define more functions in same file

When we "call" a function we usually give it input and expect output. For example:

>>a=sin(pi/2) a = 1

We gave the input pi/2 to the function sin and assigned the output to the variable a. The
function sin is not written in MATLAB code, so we cannot see how it is implemented,
though on occasion it can be useful to see how some MATLAB functions are implemented.
For example the function randperm(n) returns a random ordering of the numbers 1:n. It is
implemented in MATLAB and can be viewed by writting open randperm (your copy of
MATLAB might have a different implementation, but here's mine):

function p = randperm(n) % RANDPERM Random permutation. % RANDPERM(n)


is a random permutation of the integers from 1 to n. % For example,
RANDPERM(6) might be [2 4 5 6 1 3]. % % Note that RANDPERM calls RAND
and therefore changes the state of the % random number generator that
underlies RAND, RANDI, and RANDN. Control % that shared generator
using RNG. % % See also RNG, PERMUTE. % Copyright 1984-2010 The
MathWorks, Inc. % $Revision: 1311 $ $Date: 2012-06-18 14:27:32 -0400
(Mon, 18 Jun 2012) $ [~,p] = sort(rand(1,n));
Notice that the first line starts with the keyword function, which states that this file
contains a function rather than a script. Next comes the declaration of the return value p.
This means that the value of the variable, p when this function terminates, will be returned
as the output of the function. Next comes the name of the function. This should match the
name of the file. Now the list of input variables, only one in this case: n. So whatever the
input is when the function is called, internally it will be placed in a variable called n. Next
there's a long comment block which becomes the help file text (type help randsort and
see) and finally the actual body of the function. In this case it is one line of code, but it is
slightly strange; it turns out that you can return more than one value from a function. The
function sort normally returns the inputs vector sorted:

>> sort(rand(1,4)) ans = 0.1822 0.3957 0.4644 0.6998

But if you ask for two output variables, sort will also tell you the permutation needed to get
from the input to the output:

>> A=rand(1,4) A = 0.9473 0.1685 0.5514 0.2684 >>


[B,C]=sort(A) B = 0.1685 0.2684 0.5514 0.9473 C = 2
4 3 1 >> A(C) % Notice how we use the permutation C to PERMUTE
the elements of A ans = 0.1685 0.2684 0.5514 0.9473

As this code uses the random number generator 'rand', the results you get may be different
from these.

As the original list of numbers is random, it implies that the permutation needed to sort it is
a random, uniformly distributed permutation, and this is what MATLAB returns as the
output of the function randperm. Notice the use of the tilde character to signify that the first
return value isn't needed. This is a new expansion of the MATLAB language. If you have
an old version, the code will have a "throw-away" variable (a variable that is not used).

Vectorization and User-Defined Functions

Functions define a small world of variables that are isolated from the rest
of the "workspace". This is mostly a good thing, though you may find it
limiting at times. It is important to realize that a function can call itself,
and even then the variables inside the called function cannot interact
directly with those of the calling workspace. Here is an example to show
this:
function triangle(n) n if n > 1 triangle(n-1) end n

This is a function with no output, that calls itself. Calling it from the
command-line gives:
>> triangle(4) n = 4 n = 3 n = 2 n = 1 n = 1 n = 2 n = 3 n = 4
Exercise 14: Write a function that recursively (a function that calls itself
is called recursive) calculates the Fibonacci numbers:
F1=1,F2=1,Fn+2=Fn+Fn+1

Try it out for small value of n (it will not work for large ones). (The resulting sequence is 1,
1, 2, 3, 5, 8, 13, 21, 34, 55,....)

User-defined functions are useful in providing structure to your code. When writing code
try to think in terms of functions. Separate the big task into smaller ones and define them in
terms of input and output. Your main code should then be easier to read as it will consist of
calls to the functions, each of which has a clearly defined task. Notice that in a function file,
one can define more than one function. Simply start a new line with the
keywordfunction and continue as before. This function will only be directly callable from
within the file (since the name of the file matches a different function) though there are
tricks by which one can still provide access to such "hidden" functions (too advanced for
this course).

For guided practice and further exploration of scripted functions, watch Video Lecture 5:
Scripts and Functions.

Here's an example of a function that calculates and plots the solution to the Van-der-Pol
oscillator (must be saved into a file called VDPDemo.m):

function VDPDemo(mu) % solve an ODE using Runge-Kutta 4/5:


[t,X]=ode45(@dXdt,[0,100],[0;1]); % plot the resulting phase plane
trajectory: plot(X(:,1),X(:,2)) % Here we define the derivative
function. % By nesting this function inside the main one, we get access
to the % variable mu, defined in the outer function function dX=dXdt(t,X)
x=X(1); v=X(2); dx=v; dv=-x+mu*(1-x^2)*v;
dX=[dx;dv]; end % of dXdtg end % of VDPDemo % Were the function dXdt
defined here, (after the end keyword that closes % the VDPDemo function)
the variable mu would be undefined and the code % would not run.

We can run this function by calling it with the value for mu from the command prompt:

>> VDPDemo(2)

which results in the figure:


Plotting the solution to the Van-der-Pol oscillator.

Exercise 15: Run the Van-der-Pol oscillator several times with various input values.
Observe the change in shape.

Change the code for the Van-der-Pol oscillator:

 Add a green marker at the beginning of the trajectory


 Add a red marker at the end of the trajectory
 Plot an approximation of the "limit cycle" in black
 (Bonus) find out what the period of the limit cycle is, modify the function so that it
returns this value, write an additional function or script that calls VDPDemo for
many values of mu and plots the dependence of the period on mu. Perhaps, to find the
period of the limit cycle, you can write a function that accepts an approximation to
the period of the limit cycle and returns a positive number if it's too big and a
negative number when it's too small. you can then use this function with a secant
method root finder, to find quickly the period of the limit cycle.

(Hint 1: Read the helpfile for plot carefully to understand how to change the defaults)
(Hint 2: Remember that to plot several plots on the same figure without erasing the
previous figure you need to issue a hold on command.)

Homework 3. Debug this code. Put a break-point on the first line in the inner function and
run the code (with input 2 for example). Step over ode45 and see how you can see the
values of variables by "hovering" the mouse pointer over the variable in the editor. This
only works if the variable can be "seen" from the current scope. Click "step" a few times to
see the code advancing.

Now terminate this execution.


Change the code so that the function dXdt is defined outside the main function (by moving
one end placement). Debug again and notice how the variable mu is no longer visible inside
the function dXdt. At what point does the code fail?

For guided practice and further exploration of debugging, watch Video Lecture 6:
Debugging.

Fractals and Chaos

Generating fractals is a comprehensive way to utilize MATLAB®’s


programming loops and logical expressions.

A fractal is a geometric figure that can be subdivided into parts that are
mathematically similar to the whole. You will be asked to plot the
Mandelbrot fractal, and effectively practice constructing while loops,
which terminate based on a known and specified condition. You will also
learn how to use commands that help you terminate the loop prematurely
and otherwise modify the execution of the loop.

In this unit, you will also use comparative and logical operations to evaluate expressions
and create a truth matrix composed of zeroes and ones. The truth matrix will be useful for
logical indexing, which can be used in situations that require that certain elements of a list
be separated from the rest of the elements based on a certain characteristic.
Logistic Equation

Homework 4. For r varying between 0 and 4, find out the possible "limit
cycles"§ of the iterative map:
(1)xn+1=rxn(1−x),x0=0.5(or anything else that is not 0 nor 1)

This converges to a single value for some values of r but for others results in an "orbit",
which can be very long. For every 0<r<4, "find" this orbit and plot the orbits together.

Use the "matrix-at-a-time" notation we learned in the last iteration example:

 Start with a vector of r−values, and a vector of x−values (both row vectors and the
same size).
 Perform many (how many?) iterations on the whole vector of x−values, so that each
place in the vector is updated according to its appropriate r.
 Plot the resulting x-values vs. the r values.
 Continue the iteration and plot several more iterations (how many?).
 Observe the nice pattern that arises, and explore its self-similarity properties.

Hint 1: (Am I getting the right answer?) The result should look something like this:

Graphing an iterative function.

Hint 2: (Code takes forever) If your code is running very slowly, you should consider
updating all the orbits (one for each r value) at once. This implies holding a vector that
corresponds to the r values you are considering, and a vector corresponding to the various
orbits, and with one line of code you can update all the values in the orbit. Do this in a loop
to find "late" elements of the orbit.

Hint 3: (Getting a similar plot, but not quite) You should only plot the late elements, so
perhaps iterate without plotting for some time (maybe 1000 iterations?) and then plot
successive elements of the orbit (say 100?).

Hint 4: (I don't have so many points in my plot) Be sure to use hold on so that each plot
doesn't erase the previous ones.
More ideas:

 Find how to make the plot have small dots as markers.


 Can you allow the user to "zoom in" on your plot? Once asked to see a region
smaller than (0,4)×(0,1) you should probably increase the "density" of
your r measurements, and confine the plotting of the points so that only the
requested x's are plotted.
§
a limit cycle is an orbit of an iterative map that the dynamics of the problem converges to,
regardless of the initial condition.

More on loops

The for loop is a very useful tool for doing things over and over again
for a certain number of times already known in advance. There are two
possibilities that we would like to consider:
 What if we do not know in advance how many iterations we will need?
 What if we would like to stop a loop before it is due to end?
An example for the first kind would be a Newton iteration that should run until the value
of f(x) is "small" enough, for example 10−12. Before actually performing the iterations we do
not know how many steps it will take, so a for loop is not exactly the right type of loop.
We could get around this limitation if we introduce a maximum number of allowed
iterations and then use the (as-of-yet unknown) mechanism for terminating a loop
prematurely once we find a good enough approximate root.
A while loop tells MATLAB® to continue iterating as long as a certain condition (which
you specify) is satisfied. The syntax is:
while <condition> <statements> end
MATLAB evaluates the <condition> and if it is true (or a non-zero number) it
performs the <statements>, if not, it continues after the end. After each time it
evaluates <statements> MATLAB goes back and evaluates <condition> again,
etc. Note that <condition> does notget evaluated in the middle of
evaluating <statements> but, rather, only before evaluating them. Here's a simple
way of adding two positive integers (very silly):
x=5; y=6; while y>0 x=x+1; y=y-1;
end
Of course, this fails miserably if y is not a positive integer (doesn't do anything, do you
understand why?)
Exercise 16. Solve the following problems using a while loop:
 Show the numbers from 1 to 10
 Show the numbers from 10 to -10
 Find out how many divisors 28 has (mod or rem will be useful here)
 Find out if a number is prime
 Use an external while and an internal for loop to find the first 100 prime numbers.
 A perfect number is a number n whose divisors (including 1 but excluding itself) add up
to n itself. For example, 6 is a perfect number. Check if a number is perfect.
 Use two nested while loops to find the first 3 perfect numbers.
Homework 5. Consider the following sequence defined completely by the first element S1¶:
A still|| open question in mathematics is whether all such sequences always arrive at 1 for
large enough n (the alternatives being that some sequences may rise indefinitely, or that
there may be a closed orbit that does not include 1). Compute the number of iterations it
takes to arrive at 1 given a starting value s using a while loop. Since we do not know how
long it will take to arrive at 1 (though you can assume that it will happen eventually) we
might want to construct this sequence using a while-loop. What starting number smaller
than 10,000 has the longest trajectory? What's the largest number on that trajectory?
§
This is the subject of the Collatz Conjecture.
||
Despite a recent "near" solution.

Terminating a Loop Prematurely: Break and Continue


As you may recall, a while loop will evaluate all its statements without
checking the condition. Similarly a for loop will run through all of its
iterations. The break keyword tells MATLAB® to exit the loop
immediately. It will only terminate one loop (in the case of nested loop,
the innermost one it is in) and will normally be protected by
an if statement (otherwise the loop is silly). Here is an example that
computes the "trajectory" of 6 but stops if it finds a 17 in it:
s=6; % initialize s to 6 while
s~=1 % as long as s is not equal to
1 stay in the loop if s==17 % if s
equals 17 sprintf('Found 17 in
the loop!!') break; end
if mod(s,2) % the actual "brains" of the
iteration s=s/2; else
s=3*s+1;
end end
The keyword continue is similar but different. It avoids the rest of the statements of the
inner most loop, but continues in the loop (does not stop like break).
Here's example code for a while loop that uses both break and continue to find the first
100 primes (not very efficiently, but it's only an example):
n=1; m=0; while 1 % this means that
unless we use "break", the loop will
continue "forever" n=n+1; % increase
n flag=0; % reset flag for
i=2:ceil(sqrt(n)) % no need to check
numbers greater than the square-root of n
if mod(n,i)==0 % means that i divides n
exactly flag = 1 % to
know that we found a divisor
break; % no need to remain in the for
loop end end if flag
continue % to avoid the next line. It
could have also been done
% differently with an "if" statement, but
this can be more elegant end
sprintf('%d is prime!\n',n) % this is
quite an interesting command...
% take some time to learn about it
m=m+1; % increment primes count
if m>=100 % if we have enough
break; % stop looking for primes end
end
Homework 6. The keywords break and continue are not "needed'' per se, but they
can make the code more elegant and readable. Rewrite the above code for the first 100
primes without using neither continue nor break.
Homework 7. for loops and while loops are not inherently different:
 The "input" of a for loop is a variable and a vector of values. Recreate the
functionality of a for loop using a while loop.
 The "input" of a while loop is the condition statement. Recreate the functionality of
a while loop using a for loop. (Hint: when using the notation for
i=1:n MATLAB does not actually create the vector 1:n. Internally it simply iterates
over the values in that vector by incrementing i until it reaches n. This means that if
you write for i=1:281474976710655 you'll get a loop that, on its own, will
"never" terminate. Explanation: 281474976710655 is the largest integer that MATLAB
can represent internally. It is such a large number that even if every pass through the
loop only takes 1 millisecond getting through the loop will take about 10000 years.)
Truth Statements and Logical Indexing
The Mandelbrot Set is the set of points z∈C for which the sequence
remains bounded as n→∞. Color can be added for the unbounded elements by specifying
how "fast" they diverge, for example, how many iterations it takes to reach some large
absolute value. (Since once |xn| is large enough the sequence will be growing indefinitely.)
To decide on the color of a particular point on the screen (x,y), we define a complex
number z=x+iy and iterate according to the equation mentioned above.
Exercise 17. With three nested for loops, iterate over x=-1.5:.01:0.5 and y=-
1:0.01:1. For each point, iterate, say, 100 times andbreak if abs(z_n) is ever too
large, say larger than 10. There's no need to keep the sequence of z's, but be sure not to
overwrite the z variable that comes from x+iy. If the the sequence grew to be large, leave
white, otherwise place a black dot at (the original) (x,y).
The result should look like this:

Conway Game of Life

Example of Conway’s Game of Life after multiple iterations of Conway’s


Game of Life. (Photograph courtesy ofdjspyhunter on Flickr.)

This unit challenges you to employ the skills that you have acquired in more complex tasks,
as well as in a larger coding project. The project is an implementation of the Conway Game
of Life, in which cells in a 2D grid are labeled as either "alive" or "dead." The game runs
according to a defined set of rules, and you will be responsible for calculating each state of
the cells, updating the grid, and plotting the grid. Other avenues of exploration and
variations to the game are also proposed for your implementation.
In all the following questions you are expected to have an "elegant"
solution, not a brute force one. No if statements or loops. Unless where
specifically noted, no MATLAB® functions are to be used.
1. Find out what the command diag does. (We already learned about ones, zeros,
and sum, but if you are unsure, look them up as well.) Using sum and diag, find the
sum of the diagonal of a matrix. (For example, A in the next question.)
2. Let A=magic(6). What expression will give you the 2×2 submatrix of elements in
the upper left corner? How about lower right? Can you write an expression that will
also work for any other matrix A, for example A=magic(10)?
3. Find the sub-matrix of elements of A whose both coordinates are odd.
4. With no MATLAB functions, write the matrix A "flipped" right to left. Up to down.
5. Get the sum of the "anti diagonal" of the magic square by a simple expression
using sum, diag and the colon (:) notation.
6. Let x = [2 5 1 6]. Add 3 to just the odd-positioned elements (resulting in a 2-
vector). Now write the expression that adds 3 to the odd-positioned elements and puts
the result in the even positions of the original x vector.
7. Let y = [4 2 1 3]. Think of y as a specific reordering (permutation) of the
numbers {1,2,3,4}. "4 goes to 1, 2 remains, 1 goes to 3 and 3 goes to 4." Use y to reorder
the elements of x in the same manner. (The result should be [6 5 2 1].)
8. What is the vector that corresponds to the permutation of n elements that takes every
element one position to the left, except for the first element, which goes to the end?
9. (Bonus) The inverse of a permutation y is a permutation z that, when combined
with y (in either order) gives the original (non-permuted) elements. Given a
permutation vector (as y is in the previous question), find the vector z which
corresponds to the inverse of y.
10. Experiment with assignments such as b(1:3,1:2:4)=1. Make a "checkerboard"
matrix: an 8-by-8 matrix whose cell a(i,j) equals 1 if i+j is odd and 0 if it is even. (Of
course, do not use loops or if statements!) If you like, use the
function spy or pcolor to "see" the checkerboard that you created. (Tricky. Do it in
two commands, not one. If you want to do this with one command you may use ones.
Also possible usingmod and reshape.)
11. Recall that a matrix (such as A) can also be referenced using a single
coordinate: A(3). Remind yourself how this coordinate is related to the original
matrix.
12. Use the single index reference to a matrix in order to extract the diagonal of a 5-by-5
matrix. (Do not use the function diag.) Do the same to extract the "anti-diagonal".
Conway Game of Life Implementation
This project implements the Conway Game of Life. Idea: The world
consists of a 2D grid. Each cell in the grid can be "alive" or "dead". At
each step the cells are updated according to the following rules:
 A dead cell will become alive if it has exactly 3 live neighbors (each
non-boundary cell has 8 neighbors in this grid).
 A live cell will die unless it has 2 or 3 live neighbors.
We use a matrix to hold the grid. A cell is "alive" if the relevant matrix
element is 1 and "dead" if 0. Several steps are needed:
1. Figure out how many live neighbors each cell has.
2. Update the grid.
3. Plot the grid.
Homework 9. Implement the Conway Game of Life by iterating over all
the grid cells and for each one counting the neighbors. You can either be
careful not to access elements that are beyond the limits of the matrix, or
make the matrix slightly larger and only iterate over the "middle" part of
the matrix. Start with a small grid, as this is a very inefficient method
upon which we will improve. To plot the grid use pcolor. Make sure
you first calculate the number of neighbors and then update the grid,
otherwise your update of early cells will interfere with the calculation of
the later cells.
As you can easily see when trying to increase the size of the grid, this is a very inefficient
method. We want to do all the tasks on a matrix-at-a-time basis, with no
unneeded for loops.
The hardest part of the calculation is the neighbor-counting part. Here's one way to do this:

Noff_r= [-1, -1, 0, 1, 1, 1, 0, -1];


%the row offset of the 8 neighbors Noff_c=[ 0,
1, 1, 1, 0, -1, -1, -1]; %the column offset
of the 8 neighborsn N=numel(Noff_r); % the
number of neighbors each element hascount =
zeros(size(A)-[2 2]); %A is the grid with a
border of zerosfor j j=1:n N
count=count + A(Noff_r(jj)+(2:end-
1),Noff_c(jj)+(2:end-1)); %this is the
heartend %now count will have the correct number
of alive neighbors.
Exercise 20. It takes time and practice to understand code. Explain to a friend, or a
classmate how this code works.
Exercise 21. Here are various parts of the next step:
 Given the matrix count find the logical expression that informs which elements
of A(2:end-1,2:end-1) have 2 or 3 neighbors.
 Find the truth matrix specifiying the elements that need to "die" according to
the count.
 Find the truth matrix specifiying the elements that need to be "born" according to
the count.
 Find the elements that are alive and need to remain so.
 Update A according to the rules.
 Show the grid using pcolor.
Homework 10. (Bonus) Counting neighbors can be done as a single linear algebra
multiplication of A(:) by a large, mostly empty matrix. Figure out how this is possible,
and implement it. Since the matrix is so large, use a sparse matrix.
Project 3. Now that we have all the parts (refer to Homework 9, Exercise 20, Exercise 21,
and Homework 10), here's the project: Initialize the board using rand. Put the counting,
updating, plotting parts of the game into a loop. When busy calculating MATLAB® avoids
updating the plots. To force MATLAB to update the plots, place
a pause(0.1) after pcolor.
Once you have the basic dynamics working, there are various directions for further study:
 You will find that a large grid still requires too much memory and computation time.
Since the matrices A and count are mostly zeros, it can be beneficial to use
a sparse matrix for them. Figure out how to do it. To get a random sparse matrix
use sprand.
 What happens if you change the rules? You can change the birth/life/death rules, or you
can change the definition of neighborhood, or both. Find an alternative dynamic with
nice results.
 A square grid is only one possibility. You could also consider a triangular or hexagonal
grid. How would you implement them? Can you find nice game rules for them? How
would you plot them? You cannot use pcolor any more.

More Projects

From the lecture material, you have already completed three coding
projects that have asked you to plot the basins of attraction, optimize the
basins of attraction code to run faster, and fully implement the Conway
Game of Life. Now, each of the following is an idea for a project. The
projects are left relatively vague and open-ended on purpose. It is your
job to find projects you like and "run" with them. Some of the projects
consist of a well-defined part and a lesser-defined part. The defined part
should be thought of as the introduction to the topic, not the project
itself. The project inherently includes a vague part that the student will
need to define on his or her own.

Queens on a Chessboard (PDF)

Cursive Spline (PDF)

Autostereograms (PDF)
Brownian Motion (PDF)

Command Prompt and Expressions

At its heart, MATLAB® is a big calculator. To calculate something simply


type it in at the "command prompt" and press Enter. Thus, to calculate 1
+ 1 we type it in and press Enter. The screen should show:
>> 1+1 ans = 2

meaning that the answer is 2.

Exercise 1. Run MATLAB, find the command window and the blinking
cursor. Find the answer to the following arithmetic problems:
 1234+4321=?
 104−765=?
 47∗33=?
 34=? (The operator for "power" is the circumflex ^, usually found by pressing Shift
⇑6
 How far is 192 from its approximation 202−2∗20 (Remember
that (a−b)2=a2−2ab+b2, thus the answer should be ±1)
 Find an approximation to 1/73
 Find an approximation to 31 (while you can of course use the fact that x=x0.5, you
can also "look for" a dedicated function square root by learning how to use
the lookfor command....)
 If you get 5% interest-rate (yearly) on a loan, compounded monthly, and you start
with $1000, how much money will you have after 20 years? (don't be confused by an
answer of the form 2.7e3 which simply means2.7×103)
 If two sides of a right triangle have lengths 31 and 45, what is the length of the
hypotenuse?

You may have noticed in the exercises that the answer is only given with 5 digits of
accuracy (at most). For example, we can ask MATLAB for the value of π and get:

>> pi
ans =
3.1416

Internally, MATLAB keeps a 16 (more-or-less) digit version of the number it shows us, but
to keep things orderly, it only displays the answer rounded to show 5 digits (by default).
We can change this by issuing a command:

>> format long


>> pi
ans =
3.141592653589793

We can see this, by subtracting part of π from ans, which always holds the full, unrounded
answer to the previous, unassigned expression:

>> format short


>> pi
ans =
3.1416
>> ans-3.1415
ans =
9.2654e-05
>> ans - 9.2653e-5
ans =
5.8979e-10

Exercise 2. Remember the cosine rule? c2=a2+b2−2abcos⁡(θ). Find the length of the
hypotenuse of a triangle with angle 30ο, and sides with lengths 10 and 20.
The MATLAB trigonometric functions (cos, sin, tan) use radians, so you will need to
convert using π.

For guided practice and further exploration of how to use the command prompt,
watch Video Lecture 2: The Command Prompt.

MATLAB Teaching Codes

The MATLAB Teaching Codes consist of 37 short, text files containing


MATLAB commands for performing basic linear algebra computations.
These Teaching Codes are available as a single tar file, or as individual
text files. You can download the Codes to your computer in two different
ways. [1] To Download The Teaching Codes As A Single Tar File (a) Click
on Tcodes.tar to access the tar file. (b) With most browsers (Netscape,
Explorer) a dialog box now appears, and you can specify in which
directory to save the tar file. (c) Within a terminal window, move to the
specified directory and unpack the tar file by typing the command: tar xvf
Tcodes.tar A new directory called Tcodes is created, and it contains all of
the MATLAB Teaching Codes. [2] To View Or Download A Particular
Teaching Code The name of each MATLAB Teaching Code is listed below.
To VIEW a particular Teaching Code: click on its name. To DOWNLOAD a
particular Teaching Code: click on its name, then use the menus on your
Web browser to save the file to your computer. For example, most
browsers (Netscape, Explorer) have a FILE menu. Underneath the FILE
menu is a SAVE command that you can select. Usually, a dialog box then
appears and you can specify in which directory you wish to save the text
file.

cab.m............Echelon factorization A = c a b.

cofactor.m........Matrix of cofactors.

colbasis.m........Basis for the column space.

cramer.m............Solve the system Ax=b.

determ.m........Matrix determinant from plu.

eigen2.m............Characteristic polynomial, eigenvalues, eigenvectors.

eigshow.m............Graphical demonstration of eigenvalues and singular values.

eigval.m............Eigenvalues and their algebraic multiplicity.

eigvec.m............Eigenvectors and their geometric multiplicity.

elim.m............EA=R factorization.

findpiv.m............Used by plu to find a pivot for Gaussian elimination.

fourbase.m............Bases for all 4 fundamental subspaces.

grams.m............Gram-Schmidt orthogonalization of the columns of A.

house.m............Stores the "house" data set in X.

inverse.m............Matrix inverse by Gauss-Jordan elimination.

leftnull.m............Basis for the left nullspace.

linefit.m............Plot the least squares fit by a line.

lsq.m............Least squares solution of Ax=b.

normal.m............Eigenvalues and eigenvectors of a normal matrix A.

nulbasis.m............Basis for the nullspace.

orthcomp.m............Orthogonal complement of a subspace.

partic.m............Particular solution of Ax=b.


plot2d.m............Two dimensional plot.

plu.m............Rectangular PA=LU factorization *with row exchanges*.

poly2str.m............Convert a polynomial coefficient vector to a string.

project.m............Project a vector b onto the column space of A.

projmat.m............Projection matrix for the column space of A.

randperm.m............Random permutation.

rowbasis.m............Basis for the row space.

samespan.m............Test if two matrices have the same column space.

signperm.m............Determinant of the permutation matrix with rows ordered by p.

slu.m............LU factorization of a square matrix using *no row exchanges*.

splu.m............Square PA=LU factorization *with row exchanges*.

splv.m............Solution to a square, invertible system.

symmeig.m............Eigenvalues and eigenvectors of a symmetric matrix.

tridiag.m............Tridiagonal matrix.

LECTURE NOTES CONTENTS FILES

Lecture 1: Introduction to MATLAB Basics

 Getting MATLAB to Run


 Programming Lecture 1 Notes and
 The Command Prompt Exercises (HTML)
 Simple Expressions
 Variables
 Referencing Matrix Elements

Lecture 2: Matrices
Lecture 2 Notes and
 Accessing Matrix Elements Exercises (HTML)
 Assigning into Submatrices
LECTURE NOTES CONTENTS FILES

Lecture 3: Basic Tools

 Matrix Concatenations Lecture 3 Notes and


 More Expressions Exercises (HTML)
 Plotting
 Logical Constructs
 Formatting Text

Lecture 4: Flow Control


Lecture 4 Notes and
 "if" Statement Exercises (HTML)
 "for" Loops

Lecture 5: Defining Functions


Lecture 5 Notes and
 "while" Statements Exercises (HTML)
 Variable Scope

Lecture 6: Functions and Logic


Lecture 6 Notes and
 Multiple Input Functions Exercises (HTML)
 More on Logic

You might also like