You are on page 1of 14

# Intro to Numerical Methods

APAM E4300(1)
ASSIGNMENT 1 – SOLUTIONS (INTRODUCTION TO MATLAB)
Due: Tuesday, February 12, 2013
Problem 1 [9 points]:
a) Use MATLAB to produce a single plot displaying the graphs of the functions sin(kx)
across [0, 2π], for k = 1, … , 5.
b) Use MATLAB to print a table of values x, sin(x), and cos(x), for x = 0, π/6, 2π/6, … ,
2π. Label the columns of your table.
c) Plot each of the functions below over the range specified. Produce 4 plots on the
same page using the subplot command.
a. f(x) = |x-1| for -3 ≤ x ≤ 3. (Use abs in MATLAB)
b. f(x) = || for -4 ≤ x ≤ 4. (Use sqrt in MATLAB) 

c. f(x) =   for -4 ≤ x ≤ 4. (Use exp in MATLAB) 

d. f(x) =
for -2 ≤ x ≤ 2.  

 

Solution:

a) x = [0:.01:2*pi];
plot(x,sin(x),x,sin(2*x),x,sin(3*x),x,sin(4*x),x,sin(5*x))
legend('sin(x)','sin(2x)','sin(3x)','sin(4x)','sin(5x)')
xlabel('x')
ylabel('sin(kx)')
1
sin(x)
sin(2x)
sin(3x)
sin(4x)
sin(5x)

0.8
0.6
0.4

sin(kx)

0.2
0
-0.2
-0.4
-0.6
-0.8
-1

0

1

2

3

4
x

5

6

7

01:2]. cos(x)).b) fprintf(' x sin(x) cos(x) \n') for x=0:pi/6:2*pi.2.4 0. fx = abs(x-1).2.4f %8. fx = 1 .6 0.2. x.8 0. c) The following code produces the plots below: % (a) x = [-3:.fx) title('sqrt(abs(x))') % (c) x = [-4:.5 0 -4 -2 0 2 4 0 -4 -2 exp(-x 2) 1 0.^2 + 1). subplot(2.4f %8. subplot(2.2) plot(x./ (10*x.4 0.2 0.01:3]. sin(x). fprintf('%8.01:4]. fx = exp(-x.4) plot(x.3) plot(x.2 -2 0 2 4 1 2 1 / (10 x 2 + 1) 1 0 -4 0 2 4 0 -2 -1 0 .^2).fx) title('1 / (10 x^2 + 1)') abs(x-1) sqrt(abs(x)) 4 2 3 1.fx) title('exp(-x^2)') % (d) x = [-2:.fx) title('abs(x-1)') % (b) x = [-4:.6 0. fx = sqrt(abs(x)). subplot(2. end.4f\n'. subplot(2.5 2 1 1 0.01:4].2.8 0.1) plot(x.

and from this plot it appears that f(x) has three roots in this interval.456 -1.02 -1.444 -1.m from the web page and execute it.442 -1.454. Write an estimate of the value of this root to at least 3 decimal places.452 -1. The top plot shows the function f(x) = 2 cos(x) .446 -1.458 -1.454 -1. This should produce the two plots shown below. plot of 2cos(x) .02 0.01 -0. b) Edit the script from part (a) to plot the function .46 -1.Problem 2 [9 points]: Download the M-file plotfunction1.01 0 -0.45 -1. This will be important when we study numerical methods for approximating roots.exp(x) 5 0 -5 -10 -15 -20 -25 -6 -5 -4 -3 -2 -1 0 1 2 3 zoomed view 0. showing that f(x) has a root near x = -1. Note also that when we zoom in on this function it looks nearly linear over this short interval.448 -1. You may find it useful to first use the zoom feature in MATLAB to see approximately where the root is and then to choose your axis command for the second plot appropriately. Note the different vertical scale on this plot.44 a) Modify this script so that the bottom plot shows a zoomed view near the leftmost root.ex for -6 ≤ x ≤ 3. The bottom plot is a zoomed view near one of these roots.

  4 · .

^2). Write an estimate of the value of the root from the plots that is accurate to 3 decimal places.3) . Note that once you have defined the vector x properly./ (2 + x. .  3 2   over the range 0 ≤ x ≤ 4 and also plot a zoomed view near the leftmost root.*sin(x) . you will need to use appropriate component-wise multiplication and division to evaluate this expression: y = (4*x.

exp(x)') % Zoom in on smaller interval about one root.718 -4.01:3].Solution: a) The root is approximately -4.0001:.7176 -4.^2)) title('zoomed view') -4.716 .7162 b) The root is approximately 0.2*cos(xx)-exp(xx)) title('zoomed view') plot of 2cos(x) .7172 -4.7174 -4. plot(x.7178 -4.934].717 -4./(2 + x. plot(xx. plot(xx.01:4].716].7168 -4. (4*xx.*sin(xx)-3). The following code produces the plot below: % Plot function over large interval.1.1. The following code produces the plot below: % Plot function over large interval.0001:-4. subplot(2.2*cos(x)-exp(x)) title('plot of 2cos(x) . (4*x.exp(x) 10 0 -10 -20 -30 -6 -5 -4 -3 -3 3 x 10 -2 -1 0 1 2 3 zoomed view 2 1 0 -1 -2 -4.1) x = [0:.718:.1.2) xx = [-4.933:.2) xx = [. subplot(2.^2)) title('plot of (4x sin(x) . subplot(2. plot(x.933.1) x = [-6:.717. subplot(2.3)/(2 + x^2)') % Zoom in on smaller interval about one root.*sin(x)-3).7166 -4.1./(2 + xx.7164 -4.

5 2 2.) Add the following commands to keep consistency between plots in the animation: axis([-0. The M-file contains all the necessary commands to create the fractal.5 4 zoomed view x 10 1 0.9338 0.5 0 -0.5 -1 0.5 -1 -1. axis equal .9334 0. which you will find on the web page.9336 0.75 -sqrt(3)/6 1]).5 -3 1.5 0 -0.5 1 1.934 0.5 0 0.9342 Problem 3 [9 points]: In this exercise. (Hint: This can be accomplished by adding a plot command just before the completion of the outer for loop. This exercise uses the MATLAB M-file koch. which is depicted below.m.75 0.3)/(2 + x 2) 1 0. Edit this M-file so that each stage of the fractal is plotted. except for the necessary plotting commands.933 0.5 3 3.9332 0. you will plot initial stages of a process that creates a fractal known as Koch's Snowake.plot of (4x sin(x) .

v(4*j .1) = x(j) + 1/2*dirx + 1/3*1/2*sqrt(3)*orthox. v(4*j .2) = y(j) + 1/3*diry. for i = 1:n.x(j).3) = x(j). orthoy = dirx. end v(4*k-3) = x(k). y = w.Note that the cla command clears the axes. dirx = x(j+1) . v(4*j . as opposed to plot.) Solution: The following modified code plots the stages of Koch's snowake. n = 4. v(4*j) = x(j) + 2/3*dirx. w(4*j . %% Added lines for plotting subplot(2. k = length(x).y) axis([-0. pausing briefly after each stage: % Plot stages 0 through n of Koch's Snowflake % % For more information on Koch's Snowflake.75 -sqrt(3)/6 1]) axis equal title(['Stage '.5) in appropriate places to slow the animation.int2str(i)]) pause(0.y(j). w = zeros(4*k-3). add the command pause(0.com/KochSnowflake. w(4*j .wolfram. y = [0 1 0 0]. w(4*k-3) = y(k). orthox = -diry.1) = y(j) + 1/2*diry + 1/3*1/2*sqrt(3)*orthoy. for j = 1:k-1. Finally. v = zeros(4*k-3).3) = y(j). see: % http://mathworld. i) plot(x. w(4*j . (The fill command. produced the filled fractals depicted above. diry = y(j+1) .2) = x(j) + 1/3*dirx. x = v.5) end . w(4*j) = y(j) + 2/3*diry.html % x = [-1/2 0 1/2 -1/2]. 2.75 0.

6 0. any column.4 0.) b) With the following matrices and vectors: Compute the following both by hand and in Matlab.Stage 1 Stage 2 0.6 0.5 -0.2 0.5 0 0.5 0 0. use the diary command to record your session.2 -0. a) b) c) d) e) f) v Tw vwT Av A Tv AB BA . rows and diagonals are equal. read documentation for the diag and the flipud commands.8 0.2 0 0 -0.4 0.5 Stage 4 0. For the MatLab computations.2 0.2 -0. Create a log of your session that records your work. where each number occurs exactly once.4 0.2 -0.2 -0. Create a 5 by 5 magic square and verify using the sum command in MATLAB that the sum of the columns. or any main diagonal is the same.4 0.5 0 0.8 0.6 0.6 0. (Hint: To find the sum of the diagonals.8 0. The MATLAB command magic(n) creates an n by n (where n > 2) magic square. and the sum of the entries of any row.8 0.5 Problem 4 [8 points]: a) A magic square is an arrangement of the numbers from 1 to n2 in an n by n matrix.5 -0.5 Stage 3 0 0.2 0 0 -0.

g) A2 (=AA) h) The vector y for which By=w i) The vector x for which Ax=v Solution: a) Following are the MATLAB commands (recorded using the diary command) to create a magic square and compute its row sums. and main diagonal sums: A=magic(5) A= 17 23 4 10 11 24 1 8 15 5 7 14 16 6 13 20 22 12 19 21 3 18 25 2 9 sum(A.2) % Sum of each row ans = 65 65 65 65 65 sum(diag(A)) % Sum of diagonal entries ans = 65 B=flipud(A) B= 11 10 4 23 17 18 25 2 9 12 19 21 3 6 13 20 22 5 7 14 16 24 1 8 15 sum(diag(B)) ans = 65 .1) % Sum of each column ans = 65 65 65 65 65 sum(A. column sums.

:). (-1.b) Problem 5 [10 points]: Computer graphics make extensive use of matrix operations.:) denotes the first row of U fill(U(1. type the following code to generate the original and rotated squares plotted one on top of the other. and (0.U(2. % Create a red unit square % Note U(1. theta = pi/4. In two dimensions. In MATLAB. let us rotate the rectangle with vertex coordinates (1. % create matrix whose columns contain the coordinates of each vertex. 0). (0. rotating an object is a simple matrix vector operation.:). -1) through an angle θ = π/4. a curve can be rotated counterclockwise through an angle θ about the origin by multiplying every point that lies on the curve by the rotation matrix:  cos   sin !. sin  cos  As an example. 0 1 0 -1]. 1). For example.'r') % Retain current plot and axis properties so that % subsequent graphing commands add to the existing graph . 0). U = [1 0 -1 0.

and let #  0. and 3π/2 radians about the origin. 0). Solution: a) Following is the MATLAB code and the plot that it produces: % Create matrix whose columns contain the coordinates of each vertex. verify that these matrices are inverses of each other (that is. % Perform rotation. This corresponds to multiplying first by R(θ) and then by R(-θ). sin(theta) cos(theta)]. their product is the identity) for θ = π/3 and for θ = π/4. -1) for 50 iterations. π. V(2. fill(V(1. b) Rotating by θ radians and then rotating by -θ radians leaves the figure unchanged. 0).:).'b'). 2) and (4. Edit the code above to repeatedly rotate and shrink (by the same amounts on each step) the square (again originally with coordinates (1.hold on % Set the axis axis([-2 2 -2 2]). axis equal tight. (0. Such a point satisfies the equation   1 ' )  # ' )  ' ). c) Using the trigonometric identities cos(θ) = cos(-θ) and -sin(θ) = sin(-θ ). Plot the triangles resulting from rotating the original triangle by π/2. prove that R(θ) and R(-θ) are inverses of each other for any θ.:). ( ( 2 Solve this equation to find the numerical value of this fixed point. 0 2 1]. 1). (-1. Plot all four triangles on the same set of axes. 0). d) Let R be the matrix that rotates counterclockwise through the angle π/8. U = [5 6 4. 1). (6. Note. The plot should show all of the 51 squares on the same set of axes. Using MATLAB. you must apply the rotation and translation to all the vertices of the square. R = [cos(theta) -sin(theta). e) Apply # but now after each rotation translate the square by 1 unit in the x direction and 2 units in the y direction. grid on Note that the fill command in MATLAB plots a filled polygon determined by two vectors containing the x and y coordinates of the vertices. The resulting squares should visually suggest the existence of a fixed point. Then the matrix # simultaneously rotates and shrinks an object. . V = R*U. a) Adapt this code to plot a triangle with vertices (5.9 & . and (0.

R = [cos(theta) -sin(theta).U(2.:). % Create a red triangle.'r') hold on % Set the axis.:).theta = pi/2. sin(-theta) cos(-theta)]. R*Ri . R = [cos(theta) -sin(theta). Ri = [cos(-theta) -sin(-theta). grid 6 4 2 0 -2 -4 -6 -6 -4 -2 0 2 4 6 b) Following are the MATLAB commands (recorded using the diary command): % Test if R(theta) and R(-theta) are inverses when % theta = pi/3. % Rotate through angle pi/2 three times.:).:). end.'b') % Plot the rotated triangle. % Perform rotation. axis([-2 2 -2 2]). sin(theta) cos(theta)]. U = R*U. Note U(1.:) denotes the first row of U. for i=1:3. fill(U(1. axis equal tight. fill(U(1.U(2. theta = pi/3. sin(theta) cos(theta)].

R*Ri ans = 1 0 0 1 % They are! c) d) The following code rotates and shrinks the square and produces the plot below: % Create matrix whose columns contain the coordinates of each vertex. U = [1 0 -1 0. % Create a red unit square. Ri = [cos(-theta) -sin(-theta). theta = pi/4. R = [cos(theta) -sin(theta).ans = 1 0 0 1 % They are! % Test if R(theta) and R(-theta) are inverses when % theta = pi/4. axis([-2 2 -2 2]). sin(theta) cos(theta)]. theta = pi/8.:).:). fill(U(1.'r') hold on % Set the axis. 0 1 0 -1].U(2. Note U(1. . sin(-theta) cos(-theta)].:) denotes the first row of U.

4.:).:). % Create matrix whose columns contain the coordinates of each vertex. 0 1 0 -1].5 0 0. Rhat = . fill(U(1. axis equal tight.4 0. fill(U(1.6351). shrinks. Note U(1. R = [cos(theta) -sin(theta).:).% Perform rotations and shrinkings. U = Rhat*U.U(2.8 0.4 -0. % Create a red unit square.'r') hold on .:). and translates the square and produces the plot below.2 -0.5392. grid on 1 0.U(2.6 -0.2 0 -0.5 1 e) The following code rotates. It identifies the fixed point as (-3. for iter=1:50.9*R. theta = pi/8.8 -1 -1 -0.6 0. U = [1 0 -1 0.:) denotes the first row of U. sin(theta) cos(theta)]. end.'b').

8 7 6 5 4 3 2 1 0 -1 fixedpt = -3. sin(theta) cos(theta)]. U = Rhat*U + [1 1 1 1. Rhat = .9*R. for iter=1:50. axis equal tight. fill(U(1. end.:). 2 2 2 2].2]. % Perform rotations and shrinkings. axis([-2 2 -2 2]).U(2.Rhat.:).% Set the axis.5392 4. R = [cos(theta) -sin(theta). fixedpt = A\b. b = [1.6351 -5 -4 -3 -2 -1 0 1 .2) . grid on % Find the fixed point.'b'). A = eye(2.