a matlab primer - worcester polytechnic institutegoulet/mme528_04/matlabprimer.pdf ·...

21
A Matlab Primer C. R. MacCluer February 24, 2004 §0 Interactive versus scripts There are two ways to interact with Matlab: interactively and via scripts. At the Matlab prompt, typing a request followed by Enter will return the execution of the request. In the next line, results from previous lines can be referenced and manipulated. This is step-by-step interaction with Matlab. Alternatively, when the computation is composed of a series of many calculations or will be repeated and refined, it is better to prepare a script — where all steps of the routine are prepared in advance with a plain-text editor like Notepad, with the script saved as a .m file, such as exper.m. Typing the script file name at the Matlab prompt and hitting Enter will cause Matlab to execute the steps of the script in order. Such editors are included with most implementations of Matlab. §1 Writing arrays The line of code v = [1,2,3,4,5] assigns the symbol v to a row vector with entries 1,2,3,4,5. This is also accomplished simply by setting v = 1:5. Non- integral steps can be done with v = 1:0.1:5 to accomplish v = [1, 1.1, 1.2,...,4.9, 5]. Alternatively, v = linspace(x1,x2,n) returns with a row vector of length n of equally spaced values between x1 and x2. So for example, 1:0.1:5 = linspace(1,5,41). Matrices are assigned row-by-row, separated by semicolons. Row entries are separated by commas, or optionally, a space. For example, the 3 × 3 identity matrix can be assigned to the symbol I with I = [1,0,0;0,1,0;0,0,1], or I = [1 0 0; 0 1 0; 0 0 1], or by using the built-in command I = eye(3). Or for another example, M= [1 3 1; 4 5 6] assigns M to the 2 × 3 matrix 1 3 1 4 5 6 . 1

Upload: buithuy

Post on 26-Jun-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

A Matlab PrimerC. R. MacCluer

February 24, 2004

§0 Interactive versus scripts

There are two ways to interact with Matlab: interactively and via scripts.At the Matlab prompt, typing a request followed by Enter will return theexecution of the request. In the next line, results from previous lines can bereferenced and manipulated. This is step-by-step interaction with Matlab.

Alternatively, when the computation is composed of a series of manycalculations or will be repeated and refined, it is better to prepare a script— where all steps of the routine are prepared in advance with a plain-texteditor like Notepad, with the script saved as a .m file, such as exper.m.Typing the script file name at the Matlab prompt and hitting Enter willcause Matlab to execute the steps of the script in order. Such editors areincluded with most implementations of Matlab.

§1 Writing arrays

The line of code v = [1,2,3,4,5] assigns the symbol v to a row vector withentries 1,2,3,4,5. This is also accomplished simply by setting v = 1:5. Non-integral steps can be done with v = 1:0.1:5 to accomplish v = [1, 1.1,

1.2,...,4.9, 5]. Alternatively, v = linspace(x1,x2,n) returns with arow vector of length n of equally spaced values between x1 and x2. So forexample, 1:0.1:5 = linspace(1,5,41).

Matrices are assigned row-by-row, separated by semicolons. Row entriesare separated by commas, or optionally, a space. For example, the 3 × 3identity matrix can be assigned to the symbol I with

I = [1,0,0;0,1,0;0,0,1], or I = [1 0 0; 0 1 0; 0 0 1],

or by using the built-in command I = eye(3). Or for another example, M =

[1 3 1; 4 5 6] assigns M to the 2× 3 matrix(1 3 14 5 6

).

1

Page 2: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

There many such built-in commands for generating special matrices, forexample M = diag(v) and v = diag(M).

A linear system of n equations in n unknowns, when written in ma-trix form Ax = b, is solved with the single request x = A\b via Gaussianelimination (which is more advisable than requesting x = inv(A)*b). Thissame command x = A\b will yield solutions in the least-square sense for anyoverdetermined or underdetermined systems Ax = b.

Eigenvalues of a (square) matrix A are obtained with d = eig(A), whichreturns a row vector d of the eigenvalues of A. There are many built-in usefulextensions of the command eig.

Matrices A, B of congruent shapes are added with the request A + B.Scalar muliplication is achieved with c*A. Matrix multiplication of an m×nmatrix A followed by a n × p matrix B is accomplished with C = A*B toobtain the m× p matrix C. Taking the transpose of A is accomplished witha prime A’.

If A and B are of congruent shape, then A.*B returns the matrix ofelementwise multiplication. In general, the dot before an operation yieldsthe elementwise operation. For instance, u.^v returns the vector where eachentry of u has been raised to the power given by the corresponding entry ofv. If a request is mathematically nonsensical, then Matlab often will returnwith an error message. In other cases, it will execute the most reasonableinterpretation; for example, the request v - 1 where v is a vector will returnwith a vector where 1 has been subtracted from each component of v.

§2 Scalar versus vector computations

As a rule, ‘do loops’ are replaced in Matlab by vector calculations.

Task A: Computing a list of squares

% scalar % vectorN=10; x = 1:10;for i=1:N y = x.*xy(i) = i*i;end;

y

2

Page 3: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

Task B: Graphing one period of y = sin x

% scalar % vectorN = 100; x = linspace(0,2*pi,101);dx = 2*pi/N; y = sin(x);for i = 1:N plot(x,y)x(i) = i*dx;y(i) = sin(x(i))end;

plot(x,y)

In general, the plot command plot(u,v) will plot the row (or column)of v as ordinate against the row (or column) of u as abscissa. If say v is amatrix, multiple superimposed plots will result. For a matrix M , plot(M)will superimpose plots of the columns of M against an abscissa labeled byrow numbers.

Task C: Enhancing the graph of y = sin x

Two graphs may be superimposed with the hold command. For example,to superimpose the graph of y = J1(x) onto the graph of y = sin x obtainedin Task B, merely add the lines

% superimposing graphshold on;J = bessel(1,x);plot(x,J)

Rather than plotting points connected by straight-line segments (default),one may plot instead discrete points with plot(x,y,.), or dashed lines withplot(x,y,--), and so forth; many styles are available. One may also choosedifferent colors for each superimposed graph.

One may title a graph and its axes with say title(’The graph of y

= sin(x)’), xlabel(’x’), and ylabel(’y’), as well as place text withinthe graph at specified locations with text. Matlab provides many tools

3

Page 4: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

for contructing superior presentation graphics. One can add to the list ofstandard functions by storing a function script — see the Appendix.

Task D: Graphing a parametric curve

Graph the 3-d helix x = cos t, y = sin t, z = t with the script

% parametric plotst = linspace(0,6*pi);x = cos(t);y = sin(t);z = t;plot3(x,y,z)

Task E: Graphing a 3-d surface

Graph the sinc function z = (sin r)/r (in cylindrical coordinates) withthe script

% mesh plota = 3*pi;x = linspace(-a,a);y = x;[X,Y] = meshgrid(x,y);R = sqrt(X.*X + Y.*Y) + 0.0001;Z = sin(R)./R;mesh(Z)

There are many built-in means to massage these plots.

§3 Monte Carlo experiments

Rather than obtaining an anlaytic solution to a problem, it is often enoughto merely instruct a computer to perform experiments to build up a statis-tical picture of the phenomenon. The traditional first example is ‘dartboardintegration.’

4

Page 5: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

Task A: Integration

Let us estimate the integral

∫ 1

0

e−x3

dx

by choosing random points within the rectangle 0 ≤ x, y ≤ 1 enclosing thecurve y = exp(−x3). The number of hits under the curve divided by the areaof the rectangle must approximate the area under the curve:

% Monte Carlo integrationA = 1; % area of enclosing rectangleN = 10000; % number of experimentss = 0; % initialize success counterfor i=1:N % do N experimentsx = rand; % pick a random x coordinatey = rand; % pick a random y coordinateif y <= exp(-x^3); % if .., thens = s + 1; % increment success counterend; % end if

end; % end each experimentI = s*A/N % print approximate value

The routine will return an estimate of I ≈ 0.805. The command rand

returns a random number uniformly distributed between 0 and 1.

There are of course superior numerical methods of integration for func-tions of one variable. Monte Carlo methods become more practical for inte-grating functions of many variables.

Task B: Mean time between failure

A manufactured product is composed of three components, each witha normally distributed time before failure of mean µ = 2 years and stan-dard deviation σ = 0.75. If the construct fails whenever any one of its threecomponents fail, what is the expected life of this product?

We merely build the product many times and average the failure times:

5

Page 6: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

% MTBFN = 10000; % number builtm = 0; % initialize failure timefor i=1:N % do N experimentsx = 2 + 0.75*randn; % random lifetime of 1st componenty = 2 + 0.75*randn; % random lifetime of 2nd componentz = 2 + 0.75*randn; % random lifetime of 3rd componentw = min([x,y,z]); % failure at minimum lifetimem = m + w/N; % add in lifetime for this experimentend; % end this experiment and loop back

m % print mean lifetime

The command randn returns with a normally distributed random numberwith mean µ = 0 and standard deviation σ = 1.

Task C: Testing distributions

Let us test Matlab’s Gaussian distribution generator by gathering itsoutput into bins.

% bins of dataN = 10000; % number of random callsb = -4:0.1:4; % bins definedx = randn(1,N); % a random N row vectorhist(x,b) % histogram of bin hits

§4 Images

Every m×n matrix X = [xij] with entries 0 ≤ xij ≤ W can be thought of asa back-and-white image, consisting of mn pixels, each of grayscale intensityxij, where 0 is black, W is white.

Task A: Display a matrix as an image

The Toeplitz matrix formed from the vector r = [1, 2, 3, . . . , 100] can bevisualized as an image with the following script:

6

Page 7: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

% matrix as an imager = 1:100;T = toeplitz(r);image(T)axis offcolormap gray

Task B: Importing a photo

Consider the digital photo of two llamas, Zack and Bandit, given as amatrix of pixels, stored as the file llama.jpeg. At each pixel is a triple ofred, green, blue intensities which form the color photo. (This photo can bedownloaded from http://www.math.msu.edu/∼maccluer/Farm/llama.jpeg).

X = imread(’llama.jpeg’);image(X) % the color photo will appearaxis off

This photo can be converted to grayscale with the additional steps

% converting to grayscaleX = double(X);Y = X(:,:,1)+X(:,:,2);Y = Y + X(:,:,3);X = Y/3; % adjust brightnessimage(X)axis offcolormap gray

Task C: Inhancing contrast

Suppose X is a m × n matrix of grayscale pixels. We can modify thecontrast of this image by various schemes, e.g., by thresholding, where eachpixel is set to either black or white, depending on its orginal intensity.

7

Page 8: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

% thresholdingm = max(max(X));Z = (X > m/2); % returns 1 if true, 0 if false, entry-by-entryimage(m*Z)axis offcolormap gray

Task D: Filtering images

An image X is filtered by convolving the image with a ‘deblurring’ matrixH, producing the hopefully improved image Y = H ∗ X. This convolutionis best performed by transforming to the frequency domain by means of thediscrete Fourier transform (DFT) (implemented via the fast Fourier trans-form (FFT)) where convolution becomes elementwise multiplication, thentransforming back — see [2].

% deblurring grayimage X with filter HXhat = fft2(X); % the DFT of XHhat = fft2(H); % the DFT of HYhat = Hhat.*Xhat; % entry-by-entry multiplicationY = ifft2(Yhat); % inverse DFTY = real(Y); % clean away small imaginary partsimage(Y); % display the deblurred imageaxis offcolormap gray

Task E: Morphing one image into another

We may slowly ‘morph’ one image onto another via a homotopy.

% morphing X onto Yfps = 3; % set frames per secondN = 100; % number of framesfor k = 0:NZ = (1-k/N)*X + (k/N)*Y; % the homotopyimage(Z); % compute imageaxis offM = getframe; % store this frame

8

Page 9: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

end; % loop back for next frame% play movie M once at

movie(M,1,fps) % fps frames per second

§5 Sounds

Matlab provides the capability to ‘hear’ a vector. The entries of the vectorare interpreted as sound pressure measurements sampled at equally spacedintervals of time.

Task A: Produce a single tone

% pure tonefS = 8192; % sampling freq HzL = 5; % length of tone in secondst = 0:L*fS-1; % sampling vector size for L secondst = t/fS; % sampling timesw = 2*pi*440; % radian freq for 440 Hzx = sin(w*t); % a pure tonewavwrite(x,fS,’tone’); % create the wave file tone.wav

This wave file tone.wav can now be played by the soundcard.

Task B: Produce a soothing sound

% random noisefS = 8192; % sampling freq HzL = 5; % length of tone in secondsn = randn(1,L*fS); % random row vectorn = 0.2*n; % reduce volumewavwrite(n,fS,’noise’); % create a wave file noise.wav

Task C: Synthesize an oboe

The idea is to add overtones and wind noise to the fundamental tone toapproximate the spectral content, hence the sound of the actual instrument.

9

Page 10: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

% oboefS = 8192; % sampling freq HzL = 5; % length of tone in secondst = 0:L*fS-1; % sampling vector size for L secondst = t/fS; % sampling timesw = 2*pi*440; % radian freq for 440 Hzx = sin(w*t)+ 0.1*sin(2*w*t); % fundamental plus 2nd harmonicx = x + 0.1*sin(2.8*w*t); % flat 3rdx = x + 0.1*sin(4.2*w*t); % sharp 4thx = x + 0.4*randn(1,L*fS); % wind noisewavwrite(x,fS,’oboe’); % create the wave file oboe.wav

In an exercise you are asked to refine this synthesis, choosing additionalovertones and adjusting amplitudes, until the sound is lifelike.

§6 Spectral analysis

The spectrum of data often reveals clues about the data. For example, theprice history of a commodity may be composed of hidden superimposed cy-cles, hence price-predictable. The spectrum of sampled data is obtainedvia the discrete Fourier transform (DFT), implemented as the fast Fouriertransform (FFT) — see [2].

Task A: Find the spectrum of recorded data

Assume we have sampled data taken at N equal time intervals T givenas the row vector x.

% spectral analysisxhat = fft(x); % perform the DFTr = abs(xhat)/N; % modulus of spectrumplot(r) % display the (modulus) of the spectrum

10

Page 11: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

The preceeding rather crude spectral display should be refined:

% refined displayfS = 1/T; % compute sampling frequencyf = linspace(0,fS,N); % abscissa in hertzm = 400; % min viewing freq (Hz)mf = round(m*N/fS); % rescaleM = 2200; % max viewing freq (Hz)Mf = round(M*N/fS); % rescaleplot(f(mf:Mf),r(mf:Mf))

You will notice that the spectrum magnitude is symmetric about half thesampling frequency, an artifact of sampling itself — It is impossible to dis-tinguish frequencies that are congruent modulo the sampling frequency. See[2].

§7 Defining functions

A user can add to MatLab’s zoo of build-in functions by storing a functionscript in the working directory.

Task A: Graph y = sinc(x)

Store on disk a file sinc.m consisting of the lines

function y = sinc(x)y = sin(x)./x;

One may now call the function sinc(x) in subsequent calculations, as in

% using fplotfplot(’sinc’,[-5*pi,5*pi])

or

% integrationquad(’sinc’,eps,5*pi)

11

Page 12: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

§8 Input/Output

To save all the variables constructed during a session, use the save command.For example, save session1 will save all variables to the disk as the MatLabformatted file session1.mat. All these stored values can be imported duringa later session with the command load session1.

Most useful is the ability to import tables of ASCII data generated byother software tools. The command load file.ext followed by A = file

will bring a table of ASCII data stored on disk as the file (say) file.ext intoa MatLab session as the matrix A.

All subsequent steps during a session can be recorded for later perusalwith the command diary.

References

[ 0 ] Online help is available at the Matlab prompt, e.g., help plot returnswith the reference manual page on the plot command.

[ 1 ] C. R. MacCluer, Boundary Value Problems and Orthogonal Expan-sions, IEEE Press, Piscataway, NJ, 1994.

[ 2 ] C. R. MacCluer, Industrial Mathematics, Prentice Hall, Upper SaddleRiver, NJ, 2000.

[ 3 ] C. F. Loan,Introduction to Scientific Computing, 2nd. ed., PrenticeHall, Upper Saddle River, NJ, 2000.

[ 4 ] G. Lindfield and J. Penny, Numerical Methods using MATLAB, 2nd.ed., Prentice Hall, Upper Saddle River, NJ, 2000.

[ 5 ] Mathworks Inc., MATLAB Reference Guide, Mathworks, Natick, MA,2000.

[ 6 ] Mathworks online help at

http://www.mathworks.com/access/helpdesk/help/helpdesk.shtml

[ 7 ] A. Knight, Basics of MatLab and Beyond, Chapman and Hall/CRC,Boca Raton, 2000.

12

Page 13: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

Exercises

Exercise 1* Using Matlab, solve (if possible) the system

1 2 −1 3 −2−1 3 2 6 2

1 1 6 4 32 −2 2 5 −17 0 5 3 3

x1

x2

x3

x4

x5

=

1−3

4−7

2

.

Check your answer. Experiment and report on solving overdetermined andunderdetermined systems.

Exercise 2 Find the eigenvalues and eigenvectors of the matrix of the pre-vious exercise.

Exercise 3* Consider the n× n array H = [1/(i + j − 1)], the infamous ill-conditioned Hilbert matrix. Find its condition number (via cond) and inverse(via inv) for n = 1, 2, . . . , for as long as Matlab can hold off the numericalinstabilities. Is computing H\I a better approach?

Exercise 4 Using norm, compute the L2 norm of the 5×5 matrix of Exercise1. Find a unit vector v that realizes this norm, i.e., where ‖Av‖ = ‖A‖.

Exercise 5 Superimpose the graphs of the first eight Bessel functionsJ0, J1, . . . , J7 for 0 ≤ x ≤ 6π. What do you notice about their zeros?

Exercise 6 Write your own script to find all primes less than N. Do not useisprime etc.

Exercise 7 Using rand, prepare a list of 100 random integers between 1 and1000. Sort this list into ascending order using sort.

Exercise 8* Using roots, find the zeros of p(x) = 5x4 − 3x2 + 2x − 7.Perversely, find these zeros by instead using eig.

Exercise 9* Prepare a carefully labeled 2-d graph for classroom use tocommunicate an important concept.

13

Page 14: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

Exercise 10 Vectorize the routine of Task B in §3.

Exercise 11* Superimpose the graphs of y = sgn x and the first 11 termsof its Fourier series on [−π, π]. Observe the Gibbs phenomenon at the dis-continuities.

Exercise 12* Numerically approximate via quad the value of the ellipticintegral

I =

∫ π/2

0

dθ√4− sin2 θ

to 5 places. Compare with your own Simpson routine.

Exercise 13 What is the average number of positive integral divisors of theintegers between 1 and 1000? Do this experimentally (via Monte Carlo).Check your experimental result against the actual value.

Exercise 14* Numerically solve via ode45 and plot selected solution trajec-tories (x(t), y(t)) to the system of ODEs

x = x + y − x(x2 + y2)

y = −x + y − y(x2 + y2).

Observations?

Exercise 15* Using Monte Carlo, estimate the integral

I =

∫ 1

0

x2 dx.

Experiment by varying the number of experiments. Does accruracy continueto improve? Graph accuracy against the number of trials N .

Exercise 16 Using Monte Carlo, estimate the integral

I =

∫ π

0

∫ π

0

sin6 xy dx dy.

Compare to the value obtained via dblquad.

14

Page 15: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

Exercise 17* Simulate a drunkard’s walk. As he leaves the bar at (0, 0),each step is in a random direction of length L = 1. Estimate the expectedvalue of the square r(N)2 of his distance r(N) from the bar after N steps.Estimate the expected value of r(N). Why is E[r(N)2] 6= E[r(N)]2?

Exact answer: E[r(N)2] = N.Outline: After the kth step,

(xk, yk) = (xk−1, yk−1) + (cos θ, sin θ)

where θ is chosen randomly from the interval [0, 2π].

Exercise 18* Let X be the random variable

X =X1 + X2 + · · ·+ XN√

N

where Xk is the outcome from the kth flip of a fair coin where heads yieldsthe value 1 and tails −1. Show E[X] = µ = 0 and σ2 = E[X2] = 1. But whatis its distribution? Show experimentally that for large N, X appears to benormally distributed. You will be substantiating the celebrated central limittheorem stated in any book on statistics. Use hist.

Exercise 19 In the same vein as in Exercise 1.18, an approximately normalrandom variable with µ = 0, σ = 1 is often constructed by adding together 12independent, uniformly distributed random variables with support [0, 1] andsubtracting 6. Construct such a random variable using Matlab’s uniformlydistributed rand and check its density function for normality.

Exercise 20 A product is composed of three components and will fail if bothcomponent 1 and 2 fail, or if component 3 fails. The component lifetimesare normally distributed with means µ = 1, 2, 3 and standard deviations σ =0.2, 0.5, 0.7 respectively. Find the mean time before failure of the construct.What is the standard deviation of this failure time?

Exercise 21 An integer between 1 and 10,000 is chosen randomly. Whatis the probability that it is the sum of two squares? Obtain this estimateexperimentally.

15

Page 16: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

Exercise 22 Consider all functions f from a set X of cardinality m to a setY of cardinality n ≤ m. Experimentally estimate what percentage of the fare surjective for various m and n.

Exercise 23 Experimentally verify that with probability 1, all square ma-trices are invertible.

Exercise 24 Simulate the sound of a siren.

Exercise 25 Assemble numerical evidence that the harmonic series

∞∑n=1

1

n

diverges.

Exercise 26 Experiment with Task C of §5 to synthesize more accuratelythe sound of an oboe or another instrument of your choice.

Exercise 27 Vectorize Task E of §4.

Exercise 28 Intentionally blur an image X by convolving with a randomblurring matrix B. Display the encrypted image Y = B ∗ X. Next deblurand display. Has the image lost definition?

Exercise 29 Prepare a contour map of a surface using contour3.

Exercise 30* Prepare a detailed anotated classroom slide of a surface thatillustrates an important fact.

Exercise 31 Let X be normally distibuted with mean µ = 0 and standarddeviation σ = 1. Using randn display an experimentally obtained probabilitydistribution function of the random variable Y = X2.

Exercise 32 Is Gaussian noise more soothing than uniformly distributednoise? What is your evidence?

Exercise 33* Make a movie that slowly morphs one animal photo intoanother.

16

Page 17: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

Exercise 34 Write a script that finds the greatest common divisor of anytwo integers via the Euclidean algorithm.

Exercise 35 Fit the datax 1.1 1.3 1.5 1.7 1.9y 3.4 4.4 6.7 9.2 7.3

with a cubic spline via spline — see [2]. Graph the results with the knotsdisplayed.

Exercise 36* Fit the datax 1.1 1.3 1.5 1.7 1.9 2.1y 3.4 4.4 6.7 9.2 7.2 5.1

with a quintic polynomial using polynomial regression via polyfit. Graphthe fit. Compare with the fit of a spline interpolation via spline.

Exercise 37 Using the the cubic spline routine spline, repair f(x) = |x| sothat it becomes differentiable on (−1, 1).

Exercise 38* Write your own script to solve y′ = x sin y2 subject to y(0) =√π/2 on for 0 ≤ x ≤ 1 via the Euler, Improved Euler (Heun), and Runge-

Kutta numerical methods. Tabulate your results. Compare with results fromode45.

Exercise 39 Make a movie of a wave traveling back and forth down a clothes-line.

Exercise 40* The DFT X represents the frequency content of the image X,where the lower frequency components of X are found in the upper left handcorner of X (and in the aliased congruent lower right hand corner). Lowpassfilter a grayscale image X to form an image Y by setting all entries to 0 thatlie outside an upper left hand block of X to form Y . Compare its inversetransform Y to the original image X. What aspects of the original image arelost in this filtering?

In contrast, normalize each (complex) entry of X to modulus 1 and con-sider the inverse of the result. What aspects of X are preserved?

Exercise 41 Experimentally verify the prime number theorem, i.e., thatthe number π(x) of primes p ≤ x is asymptotically x/ log x. Check yourexperimental result using primes.

17

Page 18: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

Exercise 42 Revisit Exercise 23. A matrix A is choosen at random by areal-world computer of finite precision. What is the exact probability that Ais invertible?

18

Page 19: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

Projects

Project 1 Attempt to best Matlab’s equation solver. Using large (ill-conditioned) Hilbert matrices H = (1/(i + j − 1)), select a vector x0 andset b = Hx0. Write a routine in C to solve any system Ax = b for x, ap-ply this routine to A = H, and compare with Matlab’s answer x = H\b.Compare your accuracy against the truth model x0 with various norms, e.g.,largest error in any one coordinate (‖x − x0‖∞), the sum of absolute errorsover all components (‖x− x0‖1), or especially, the square root of the sum ofthe squares of component errors (‖x − x0‖2). Can you achieve even 20% ofMatlab’s accuracy?

Project 2 Experimentally verify Levy’s theorem: Suppose ζ(x, y) is specifiedto be either 0 or 1 at each point on the boundary of the bounded domainΩ in the plane. Let u(x, y) denote the probability that a particle releasedat (x, y) in Ω, thereafter undergoing Browian motion, will exit through theboundary at a point with ζ-value 1. Then u(x, y) is a harmonic function thatagrees with ζ(x, y) on the boundary of Ω. See [1].

Project 3 State space systems that evolve in time are often modeled usingtheir proper orthogonal decomposition (POD) modes φk:

X(t) = c1(t)φ1 + c2(t)φ2 + · · ·+ cm(t)φm.

The POD modes φk are determined statistically as follows: At the jth sampletime tj, measure the state

Xj = (x1(tj), x2(tj), . . . , xm(tj))T

of the system, a m × 1 column of readings. Take n samples with n À m.Then form the m×m matrix

A =1

nΦΦT ≈ E[X ·XT ],

where Φ = (xi(tj)) is the m×n matrix of state columns Xj. The m eigenvec-tors φi belonging to the (nonnegative) eigenvalues of A (the squares of thesingular values of Φ) form an orthogonal basis for state space.

19

Page 20: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

Argue that these POD modes form the natural basis for the time evolvingstates of the system since they arise from statistical data of actual perfor-mance. Now take the other side and argue that the POD modes are irrelevantsince they are not based on physical law — after all, you could adjoin (say)a commodity price as an additional (m + 1)th state.

Experiment with a phase space proper orthogonal decomposition of a sim-ulated one-mass, two-spring, or a two-mass, three-spring mechanical system(see Figure 9.7 of [2]). Add noise with Matlab’s randn, and compute theautocorrelation modes φi. Do you recover physically meaningful eigenvaluesand modes?

Project 4 Make a stick-figure movie. Your result will be judged on artisticas well as technical merit. Add sound.

Project 5 Solve the three-body problem: Model, code, and simulate themotions of a sun and two massive interacting planets. Do the special casewhere the sun is essentially stationary and motion is planar. Assume all threemasses to be point masses. Will collisions occur? Will a planet spiral in tobe consumed by the sun? Can a planet escape the system? Plot selectedmotions. Make a movie of several of the more interesting motions.

Project 6 Using Matlab, make a movie of the vibrations of the square drumgoverned by the wave equation

utt = ∇2u, 0 < x, y < 1

subject to zero boundary conditions. See [1] for a Mathematica-generatedmovie. Also play the sound of this drum.

Project 7 (Stockman) What is the least number of pixels and greyscalelevels needed to recognize familiar faces? Take an image of Abraham Lincolnor Marilyn Monroe etc from the web. Reduce the number of pixels andgreyscale level, until the image is just recognizable, keeping the size of theimage constant. It helps to blur the sharp edges as pixels become coarser.Recognition seems possible down to 32× 32 pixels, and 3 bit greyscale. Forexample, if we start with a 256 × 256 image of 256 grey levels, then we cannext try a “128×128” image of 256 grey levels formed as follows: Each 2×2block of the input image is averaged and the average is repeated 4 times in

20

Page 21: A Matlab Primer - Worcester Polytechnic Institutegoulet/MME528_04/matlabprimer.pdf · 2004-02-24 · A Matlab Primer C. R. MacCluer February 24, 2004 x0 Interactive versus scripts

the output image — the output still has 256× 256 pixels, but each is reallya 2× 2 block of identical grey levels.

Project 8 Simulate Young’s double slit experiment via Monte Carlo. Demon-strate that as the number of released photons grow, the impacts on the screen(behind the double slit) build up a histogram similar to interference patterns,as if each photon were a wave interfering with itself.

Project 9 Analyze the two- or three-year price history of a commodity forhidden cycles after first factoring out (exponential) inflation and price creep.

Project 10 Propose a project in consultation with the instructor. Completethis project.

21