18.S997: Introduction to Matlab Programming

18.S997: Introduction to Matlab Programming
Yossi Farjoun
December 8, 2011
1
Introduction
• Structure of the course: one term, 2 hours of lecture, and 1.5 hours of lab. Throughout the
course there will be homework and for the end there will be a final project.
• Matlab is available on Athena. It is also possible to get a copy via MIT for a largely
discounted price.
• Course mostly following the official Matlab Manual, available from MathWorks.com. See
newsgroup for a link.
• Running Matlabin Athena :
athena% add matlab
athena% matlab
It takes about 30-60 secs to start up... and you’ll get a screen showing:
< M A T L A B (R) >
Copyright 1984-2010 The MathWorks, Inc.
Version 7.12.0.635 (R2011a) 32-bit (glnx86)
March 18, 2011
To get started, type one of these: helpwin, helpdesk, or demo.
For product information, visit www.mathworks.com.
For Athena-specific information, type: help athena
For product information, visit www.mathworks.com
To start the Matlab Desktop, type: desktop
>>
2
Programming
• The computer is dumb. Everything must be explicitly told.
• Different programming languages: Why Matlab!? Simple syntax, easy to get started, easy
to do graphics.
• Compiler vs. interpreter: complied languages are usually stricter in syntax, run faster,
but require “compiling”: which means first turning the code you write into machine code;
Interpreted languages are more loose in their syntax, they try to “understand” your meaning
(sometimes failing...) at run time. They tend to run a little slower but are simpler to use
and learn.
1
3
Command Prompt and Expressions
• The command prompt: (>>) what does it mean? It means that the computer is waiting to
find out what you want it do to.
• Getting help: The help, and lookfor commands. help! on its own shows a list of topics,
but help <function-name> gives help on that function. For example help sqrt. (Try it!)
• STOP!!! don’t panic! press Ctrl-C if you want to make matlab stop doing something, or
just to clear the command prompt line (instead of deleting an unneeded expression you just
wrote).
• Simple ’expressions’: 1, 1+1,4*3, written on the command line, tell Matlabto act as a
calculator and compute the answer.
• Vectors and matrices: you can eaily create matricies (and as special cases row and column
vectors) like this: [1 2], [1:10], [1, 2 3 4; 5 6, 7 8 ; 9 10 11 12]
• Sequences with step-size 6= 1: [4:0.1:5], [5:-2:-5]
3.1
Exercises
Try to solve these with a single Matlabcommand.
1. Create the vector consisting of the whole even numbers between 15 and 27.
2. Create the vector of the previous question in decreasing order.
3. Compute the length of the hypotenuse of a right triangle given the lengths of the sides. (try to
do this for a vector of side-length values x= [a b]).
4. Compute the length of the third side of a triangle given the lengths of the other two sides, given
the cosine rule c2 = a2 + b2 − 2ab cos(t) where t is the included angle between the given sides.
4
Variables
You can store calculations for use later by creating a “variable” (the name implies that you can
change the value if you want, not that the value will change on it’s own). All you need is to give
it a name (start with a letter, then use any alphanumeric combination).
• x=1 creates a variable called “x” and stores the value “1” in it. if I then type “x” I’ll get the
“1” back.
• 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”.
5
Referencing matrix elements
• Let x = [2 5 1 6]. Add 16 to each element. Compute the square root of each element.
Compute the square of each element.
• Assignment and variables: a=10, b=[1 2 3], c=magic(4) (explain magic)
• Referencing matrix elements: b(2), c(3,2), c(12) (!) , b(4) (!)
• Usually there’s no need to “declare” variables: b(4)=4, or even b(2,5)=17.
2
• If want to declare: a=zeros(5,4) will create a 5-by-4 matrix of zeros
• Going back to the colon operator: 1:10,1:2:10 100:-25:0
• Also can be used to reference a “sub matrix” c(1:3,1) or c(2,:), c(:,end-1)
• Use sub-matrix to reorganize a matrix: c(:,[1 3 2 4]) or b([1 2 3 1 2 3]) or even
c([1 2 1:5 1])
• How is c magical?, sum, diag, and transpose. (How to get the sum of the other diagonal?)
• The command clear clears all variables from memory. clear a removes a from memory.
5.1
Exercises
In all the following questions you are expected to have an ‘elegant’ solution, not a brute force one.
No if statements or loops.
1. Find out what the commands ones, eye, zeros, diag, and sum do
2. If A is a matrix, how can you get the sub-matrix of elements whose both coordinates are
odd?
3. Write an expression for the sum of the integers from 1 to 100. use Matlab’s function sum,
not the formula (n + 1) ∗ n/2.
4. Get the sum of the “anti diagonal” of the magic square by a simple expression using sum,
diag and the colon (:) notation.
5. Let x = [2 5 1 6]. Add 3 to just the odd-index elements (resulting in a 2-vector). Now write
the expression that adds 3 to the odd elements and puts the result in the even positions of
the vector.
6. Let x = [2 5 1 6] and y = [4 2 1 3]. Think of y as a specific reordering of the numbers 1:4.
Use y to reorder x in the same fashion.
7. Given a “permutation” vector as y is in the previous item. Find the vector which gives the
inverse of the permutation! (Tricky!)
8. Experiment with assignments b(1:3,1:2:4)=1, make a “checker board” 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!) Hint: using scalar expansion set the desired elements of your matrix to
1. If you like use the function spy to “see” the checker board that you created. (Tricky, Do
it in two commands, not one.)
9. 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)
6
More Expressions
• Building blocks: variables, numbers, operators and functions
• Variables: start with letter, less than 32 chars in length. case dependent
• Numbers: examples of numbers: 1 -54 0.0001 9.5456 1.6e-20 4i -3.2j Note that both
i and j are the square root of -1, and e here means *10^ hence 1.6e-20 means 1.6*10^(-20).
• Operators: + - * ^ / \(special) ’ ( ) in the usual order of precedence.
• Functions: many built-in functions like sqrt, exp, sin, log, and more (type help elfun).
Or functions that you write yourself (we will learn how to do that later)
• You can use expressions as a block in other expressions: (1+sqrt(5))/2.
3
6.1
Exercises
1. Create a vector x of the numbers from 1 to 10. Now multiply x vector by 5 (do not create a
new vector by writing 5:5:50). Using x create the vector comprised of the first 10 squares.
2. Create a vector x comprising of 100 equally spaced numbers from 0 to 2π. Create y which has
in it the values of sin(x). using plot(x,y) plot the function sin(x).
n+1
3. Create a vector x with the elements xn = [−1]
7
/(2n − 1).
More on matrices
• Concatenation
• Scalar expansion
• Useful functions for generating matrices: ones, zeros, eye, diag. Use the help command
to find out more about these functions.
• Save a matrix using the save command, load using the load command.
1. Create a matrix whose first column is the numbers 0-10, the second column is the squares of
the numbers 0-10 and the third column is 2n where n is the numbers 0-10. You can do this in
two lines if it makes the answer more “elegant”.
2. Build a table of logs like the matrix above, for 11 equally spaces numbers from 1 to 2.
3. Start with the magic square A=magic(8). Subtract 10 from it and put the result in a matrix
B. Then make the middle square of B equal to zero. (Two statements)
8
Built-in functions
• sin, cos, sqrt, exp, log.
• Evaluating functions. x = [0:0.01:pi], y = sin(x)
• Plotting functions plot(x,y)
• Displaying results using sprintf
1. string arrays: ’hello world’ !, x = ’Yossi’, x(3), x(7)+3, char(’a’:’x’)
2. Using sprintf make Matlab print out ‘Hello world!’
3. Have variable Name hold your name (for example I would type >> Name = ’Yossi’). Now use
the sprintf function to print out ’Hello your-name-here’ the sprintf command should use the
’%s’ formatting string and the variable Name. Your name should not appear in the command....
4. Use the rand command in conjunction with sprintf in order to print something like the
following text: Here is a random number between 0 and 1: 0.9501 The number should
really be random (it should change every time you run the command). use %g in the format
string to print out a decimal number.
4
9
Flow control
• logical expressions: == ~= & | < > <= >= (only for numbers. )
• for i=1:100 Read this as “for each element i in the vector 1:100...”
• logical expressions involving matrices.
• Logical data type
• Logical scripting
• The find function.
• if statements: if else end
• more for loops: for i=v where v is a vector!
• primer on script files. filename must be a legal variable name + .m and must be in the
“path”
• break keyword
• use mod (remainder) to find if n is even.
• use mod to find if n is prime. (check with isprime)
• while loops
1. Given a vector x, sum up the values of x (use a for loop, and check against the function sum(x))
2. Given a vector x, create a vector that contains the running sum of x at each position. (The i’th
element should contain the sum of the elements 1 through i of x). Do this with one for loop if
you can. Check your answer against the function cumsum(x)
3. given a vector x calculate the product of it’s elements. Remember to “start” your result variable
from 1. Check your answer against prod(x)
4. Generate the first 20 Fibonacci numbers. Create the vector comprising of the successive ratios
(fn+1 /fn ). This can be done with a single matlab command (but if you don’t see how, use a
for loop first and solve that as a separate problem). Now plot the vector of ratios using the
plot command.
5. Find the first Fibonacci number greater than 10000. (Hint use a while loop)
P∞
2
6. A bad way to find π. It is known that n=1 n12 = π6 . We will now show this and check to see
how fast the series converges.
a. Create a vector An consisting of
1
n2
for n from 1 to 220 (this may take a few seconds).
b. Create a partial sums vector S such that S(i) has the sum of the first 2i elements of An (You
may use the sum function here)
c. Now create the vector Pi (notice the capital P...don’t write over pi) which will hold your
approximation to π by solving the formula above for π and substituting the partial sum
instead of the infinite sum.
d. The error in your approximation of π is |π − P i|. Use plot(error) in order to see that the
error tends to zero. The x-axis is the index of the vector and the y-axis is the error.
5
e. In order to have an estimate on how fast the error goes to zero, we look at the log of the
error. Plot the log of the error instead of the error and notice that it’s a straight line. Figure
out (mostly on paper, but some matlab calculations will not hurt) the value of N (on the
x-axis) that would be needed to calculate π to 20 decimal places (this means that the error
will be smaller than 10−20 ...so how small will the log of the error have to be?) How many
elements would be needed to be added up to do this? Does that sounds reasonable? Can
you do it?
7. A better way to calculate π. Compute the value of π using the following series
∞
1
π2 − 8 X
=
2
16
(2n − 1) (2n + 1)2
n=1
How accurate is the sum of 28 terms of this series? Compare the error that this method has vs.
the error of the previous method. To plot another graph on the same plot you need to “hold”
the plot. you do this with the command hold on. To release the hold type hold off this will
cause the next plot command to reset the plot. How many iterations would be needed now to
get an accuracy of 10−20 ? Can you explain the horizontal line around -30?
8. Build a vector starting from the number 0.5 and have each element equal to the previous
element squared (make x have 10 elements). Now build a vector of the ratios xn+1 /x2n (this can
be done in one command, no for loops. Plot the vector of ratios and notice the nice straight
horizontal line.
9. Given that x = [1 5 2 8 9 0 1] and y = [5 2 2 6 0 0 2], execute and explain the results of the
following commands:
a. x > y
b. y < x
c. x == y
d. x <= y
e. y >= x
f. x | y
g. x & y
h. x & (~y)
i. (x > y) | (y < x)
j. (x > y) & (y < x)
10. The exercises here show the techniques of logical-indexing Given x = 1:10 and y = [3 1 5 6 8 2 9 4 7 0],
execute and interpret the results of the following commands:
a. (x > 3) & (x < 8)
b. x(x > 5)
c. y(x <= 4)
d. x( (x < 2) | (x >= 8) )
e. y( (x < 2) | (x >= 8) )
f. x(y < 0)
11. Given x = [3 15 9 12 -1 0 -12 9 6 1], provide the command(s) that will
a. ... set the values of x that are positive to zero.
b. ... set values that are multiples of 3 to 3 (rem will help here).
6
c. ... multiply the values of x that are even by 5.
d. ... extract the values of x that are greater than 10 into a vector called y.
e. ... set the values in x that are less than the mean to zero.
f. ... set the values in x that are above the mean to their difference from the mean.
12. Another exercise to show how to avoid using for loops:
a) create a 5x5 matrix whose rows are (1:5) (Hint, find a linear algebra multiplication that will
do it nicely, or treat a vector as a 1XN or NX1 matrix)
b) do the same to create a matrix whose columns are 1:5
c) use the matrices from before create a square matrix that has ones on the diagonal and below,
and zeros above.
d) Use the lower diagonal matrix to calculate the cumulative sum of the vector x = [4 6 2 3 1]
(the n’th element of the solution should be the sum of the first n elements of x). Hint: Use
linear algebra.
13. Write a short script or function that will evaluate the following function:
h(T) = T - 10
= 0.45 T + 900
when 0 < T < 100
when T > 100
14. Write a short script or function that will evaluate the following function:
f(x) = -1
= 0
= 1
10
if x < 0
if x = 0
if x > 0
More Flow Control
• Function files vs. scripts (main function name must match file name)
• Input values for functions function MyFun(input1,input2)
• Return values from functions function retval=MyFun(...)
• Variable scope
• Multiple return values function [ret1,ret2]=MyFun(...)
10.1
Exercises
1. Create two files. A function file and a script file. The function should not take any value or
return any values. In both assign a value to a variable of your choice. From the command
prompt clear all the variables (using the clear command) and then run the function. Type
who. Are there any variables around? where is the variable that you defined in the function?
do the same for the script. Is it there now?
2. Similar as in the previous problem but now in the files calculate the expression x+1 (do not
define x in the file). From the prompt clear all the variables and assign 1 to x. Now call the
function. What happened? Call the script, what happened?
7
3. To fix the function from before we need to PASS it the value for x. So add a variable argument
to the function and call it using (1). Call it using (x). Assign 2 into y and call it using (y).
Understand what’s going on.
4. Now we will define a function with two variables. Create a function file and define a function
that accept x and y (in that order) and calculates xy (and prints it out). now call it using (2,3)
and see that it prints 8. put 2 into a and 3 into b and call it using (a,b), what about (b,a)?
put 2 into a variable x and 3 into y call the function using (x,y)....now with (y,x)...get it?
5. Now create a function that takes an integer n and returns the n’th Fibonacci number.
6. Create a function that takes two matrices and returns their pointwise product and their linear
algebra product as two different return values. Try it out on [1 2 ; 3 4] and [ 1 1 ; 2 2 ].
7. write a function that accepts two numbers and checks if the first divides the second. It should
return 1 if it does and 0 otherwise. (use the rem to see the remainder of a division)
8. Now create a function that checks if a given input is prime (divide it by all the numbers that
are less or equal to it’s square-root.)
9. print out the first 100 primes. can you verify that the nth prime is of the order of n log n − n?
10. Write a script that will use the random-number generator rand to determine the following:
a. The number of random numbers it takes to add up to 20 (or more).
b. The number of random numbers it takes before a number between 0.8 and 0.85 occurs.
c. The number of random numbers it takes before the mean of those numbers is within 0.01 of
0.5 (the mean of this random-number generator).
It will be worthwhile to run your script several times because you are dealing with random
numbers. Can you predict any of the results that are described above?
11. Write a script that asks for a temperature (in degrees Fahrenheit) and computes the equivalent
temperature in degrees Celcius. The script should keep running until no number is provided to
convert. (Hint: the function isempty will be useful here, as will input.)
12. Write a function that takes an integer (n) and then computes the following based on the value
of the integer:
While the value of n is greater than 1, replace the integer with half of its value (n/2) if the
integer is even. Otherwise, replace the integer with three times its value, plus 1 (3*n + 1).
Make provision to count the number of values in (or the length of) the sequence that results.
Example calculation: If n = 10, the sequence of integers is 5, 16, 8, 4, 2, 1 and so the length is
6.
Make a plot of the length of the sequence that occurs as a function of the integers from 2 to
30. For example, when n = 10, the length is 6 while for n = 15, the length is 17. Is there any
pattern? Try larger numbers to see if any pattern occurs. Is there any integer for which the
sequence does not terminate?
13. Compute and plot the path(s) of a set of random walkers which are confined by a pair of barriers
at +B units and −B units from the origin (where the walkers all start from).
A random walk is computed by repeatedly performing the calculation
xj+1 = xj + s
(1)
where s is a number drawn from the standard normal distribution (randn in MATLAB). For
example, a walk of N steps would be handled by the code fragment
8
x(1) = 0;
for j = 1:N
x(j+1) = x(j) + randn(1,1);
end
There are three possible ways that the walls can ”act”:
a. Reflecting - In this case, when the new position is outside the walls, the walker is “bounced”
back by the amount that it exceeded the barrier. That is, when xj+1 > B, xj+1 = B − |B −
xj+1 | when xj+1 < (−B), xj+1 = (−B) + |(−B) − xj+1 | If you plot the paths, you should
not see any positions that are beyond |B| units from the origin.
b. Absorbing - In this case, if a walker hits or exceeds the wall positions, it “dies” or is absorbed
and the walk ends. For this case, it is of interest to determine the mean lifetime of a walker
(i.e., the mean and distribution of the number of steps the “average” walker will take before
being absorbed).
c. Partially absorbing - This case is a combination of the previous two cases. When a walker
encounters a wall, “a coin is flipped” to see if the walker relfects or is absorbed. Assuming
a probability p, (0 < p < 1) for reflection, the pseudo-code fragment that follows uses the
MATLAB uniform random-number generator to make the reflect/absorb decision:
if rand < p
reflect
else
absorb
end
(ofcourse you will have to supply the code that does the reflection or absorbtion)
What do you do with all the walks that you generate? Compute statistics, of course. Answering
questions like
What is the average position of the walkers as a function of time? What is the standard
deviation of the position of the walkers as a function of time? Does the absorbing or reflecting
character influence these summaries? For the absorbing/partial-reflection case, a plot of the
number of surviving walkers as a function of step numbers is a very interesting thing. It is
useful, informative and interesting, particularly if graphically displayed.
14. Create a function that generates random arrays of integers beween a and b, inclusive. Use the
definition line function A = randint(a,b,M,N) where a and b define the (inclusive) range
and M and N define the size of the output array (rows and columns, respectively).
11
Plotting
• plot(x)
• plot(x,y)
• plot(x,y,’og’,’linewidth’,2)
• hold
• figure
• subplot
• axis
• line, title, text, label
9
12
Exercises
1. Create the plot of sin(x). be sure to take enough points so that the plot is smooth.
2. Create a plot of a circle. Plot one line for the circle (not two half circles). Show the points
on the circle (say 100 of them) in green. use ’og’ for that. Using axis equal you can make it
look like a circle too! Move the axis (from command line, using the axis command) so that
the graph only shows the second quadrant.
3. plot sin(1/x) choose your points wisely so that the plot doesn’t get ragged toward x = 0. (The
plot should become very dense as this is what the function does). Zoom in (using the command
line) to the region −0.1 < x < 0.1, −1 < y < 1. change your plot so that it uses dots on the
points and no lines. zoom in again.
4. make a plot with 6 subplots in it. do it with a for loop. title the plot with sprintf. in the
small plots have sin(nx) plotted. where n = 1,2,4,8,16,32. make sure that the title describes
the function and that the function is drawn with enough points so that it is smooth.
13
13.1
Projects
Queens on a chess board
The first part was already a homework problem: Find a set-up of 8 queens on a chess-board so
that no queen threatens another. Now we extend this a little:
• How does your solution “scale”? That is, if I ask you to solve n queens on a n × n board,
will it be possible to do with your current solution or will you need to write a new one?
(consider writing one for which this is very easy).
• How long does your program take as a function of n? Is it linear t ∝ n? Polinomial, t ∝ nα
(if so, what is α?), or exponential, t = ean (if so, what is a?)? These are important questions
to ask when you are coding a program that needs to work on “large” data.
• Can you think of ways to make your code faster? Use less memory?
• Find how many different solutions (arrangements of queens that is) are there. You will
probably have to change you code to find this out. Can you also count without including
rotations and mirror symmetries?
• How many placements of n queens on a m×m board are there? Can you find a nice formula?
How about a few of the first examples? How about when m = n?
• What about other pieces? How many (truly different) ways are there to put knights on the
board?
13.2
Make your own Auto-stereogram
Ever seen these 3D posters that work when you stare at them for a while? Did you ever care to
know how they work or wanted to make one yourself? Heres your chance!
First, the theory behind autostereograms (very non-scientific). Our mind figures out the depth
of objects by comparing the angles at which our eyes see it. We can fool this mechanism by creating
a pattern that is nearly periodic in the horizontal direction, and then looking at it as if it is closer
or further away than it actually is. By staring or looking cross-eyed at the pattern, we make each
eye focus on a different copy of the repetitive pattern. However, since the patterns is repetitive
the brain assumes that it is looking at object that is located at a different depth. To create an
illusion of a 3D object we deviate from the repetitive pattern in the following precise fashion: Each
10
dot in a copy is moved horizontally with respect to the matching dot (in the repetitive pattern).
The amount in which the dot is moved is proportional to the desired depth of the illusion at the
corresponding point. In terms of coding you will need to figure out how to:
• Create a random pattern of dots (with about 50
• Create a vertical strip of the autostereogram, copy the previous dot pattern and move the
dots in proportion to the desired depth at that point. Remember that you need to keep
coping the previous strip and not the original one
• Plot your points to create the stereogram. It is useful to plot two additional large points
below your autostereogram to indicate the spacing of repetition. This will help when trying
to view the autostereogram Your input could be a matrix, a picture, or a mathematical
formula. This doesnt mean that your program should accept all of these as input, but
rather that you consider the possibilities and think about converting the input into a map,
(x, y) → z.
• Try your program first on a simple input that you know more or less what the answer should
look like, for example a simple square that is lifted from the background. Then try it on
other simple geometric objects, like pyramids and spheres. Have a 3D picture in mind and
create it.
• If your height function has a large jump, you will find that a big area with no points is
created and this will hurt the quality of the result. To avoid this you can try to locate big
empty spaces at each repetition and fill them up with random points. These extra points
should then be copied and moved with the others.
• Big jumps in the height function can also cause points to “overlap” creating dense “blobs”
of points. This, too can hurt the quality of the autostereogram. Removing points that got
overlapped (not the points doing the overlapping) is another way to improve your autostereogram.
13.3
Spline your name
Write your name∗ in cursive on graph paper (youll need to write it rather large). For each letter in
your name select 4–6 points in the letter that best “define” the letter (letters with extra strokes, t,
i, j and x, require extra care). Write down, in order, the x and y coordinates of each of the points.
Using a spline interpolation, reconstruct your name from the measured coordinates. Create a plot
of the reconstruction. Try to do as much as possible on your own. Youll need to do the following
(each can be done with some internal matlab command):
• Find the interpolating spline polynomials
• Evaluate the polynomials for other points
• Plot the resulting (x, y) curve Remember that such a curve is rarely a function y(x) but
rather each of the coordinates is a function of a third “hidden” parameter, usually marked
t. It is with respect to this parameter that x(t) and y(t) are found, but then y(t) should be
plotted versus x(t). The more of this you do “on your own” the better. If you dont know
the equation for the spline polynomials, you can probably find it online.
∗ 1If
you have a name for which the following is annoying or for any other reason, you may use a different name
or a drawing you make with one long smooth stroke
11
13.4
Random motion (or drunken walk)
Compute and plot the paths of a set of many random walkers which are confined by a pair of
barriers at +B and B (we assume that they all start at x = 0). A random walk is computed by
repeatedly performing the calculation
xj + 1 = xj + s
(2)
where s is a number drawn from the standard normal distribution (randn in Matlab). For
example, one walker taking N steps could be handled by the code fragment
x(1) = 0;
for j = 1:N
x(j+1) = x(j) + randn(1,1);
end
There are three ways in which the barriers at ±B can “act”:
a. Reflect: In this case, when the new position is outside the walls, the walker is “bounced” back
by the amount that it exceeded the barrier. If you plot the paths, you should not see any
positions that are outside the barriers.
b. Absorb: In this case, if a walker hits or exceeds the wall positions, it is absorbed and the
walk ends. For this case, it can be of interest to determine the mean lifetime of a walker (i.e.,
the mean and distribution of the number of steps the “average” walker will take before being
absorbed).
c. Partially absorb: This case is a combination of the previous two cases. When a walker encounters a wall, “a coin is flipped” to see if the walker is reflected or is absorbed.
d. Maybe you can think of some other interesting boundary condition? perhaps something nonphysical, like a teleportation of particles from the boundary to the interior?
What do you do with all the walks that you generate? Compute statistics, of course. Answer
questions like:
• What is the average position of the walkers as a function of time?
• What is the standard deviation of the position of the walkers as a function of time?
• Does the absorbing or reflecting character influence these summaries?
• For the absorbing/partial-reflection case, a plot of the number of surviving walkers as a
function of step number/time is a very interesting thing, particularly if graphically displayed.
What about the “density” of walkers? Can you plot it?
13.5
Chaos: xn + 1 = rx(x1) and the Mandelbrot set
You already found this simple formula in a homework assigment. Nows the time to take that
homework assignment to the next level.
• Find how to make the plot have small dots without plotting each data-point with a single
plot command.
• For each r the iterates converge on a finite set of values, x. Dont plot more points than you
need. Make sure you iterate enough for convergence (the original value of 1000 was only a
rule of thumb).
• 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.
12
• Can you find out how to redraw the figure whenever the zoom tool is used?
Let try making a 2-D picture. The mandelbrot set is the set of points x ∈ C for which the sequence
x0 = 0, xn+1 = (xn )2 + x
(3)
remains bounded. colors are added for the unbounded elements by specifying how “fast” they
diverge, for example, how many iterations it takes to reach some large absolute value.
Plot the Mandelbrot set and allow the user to zoom-in to part of the figure (redrawing the
figure when they do)
13