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

4
x

b) fprintf(' x sin(x) cos(x) \n')


for x=0:pi/6:2*pi, fprintf('%8.4f %8.4f %8.4f\n', x, sin(x), cos(x)); end;
c) The following code produces the plots below:
% (a)
x = [-3:.01:3]; fx = abs(x-1);
subplot(2,2,1)
plot(x,fx)
title('abs(x-1)')
% (b)
x = [-4:.01:4]; fx = sqrt(abs(x));
subplot(2,2,2)
plot(x,fx)
title('sqrt(abs(x))')
% (c)
x = [-4:.01:4]; fx = exp(-x.^2);
subplot(2,2,3)
plot(x,fx)
title('exp(-x^2)')
% (d)
x = [-2:.01:2]; fx = 1 ./ (10*x.^2 + 1);
subplot(2,2,4)
plot(x,fx)
title('1 / (10 x^2 + 1)')
abs(x-1)

sqrt(abs(x))

1.5

0.5

0
-4

-2

0
-4

-2

exp(-x 2)
1

0.8

0.8

0.6

0.6

0.4

0.4

0.2

0.2

-2

1 / (10 x 2 + 1)

0
-4

0
-2

-1

Problem 2 [9 points]:
Download the M-file plotfunction1.m from the web page and execute it. This should
produce the two plots shown below. The top plot shows the function f(x) = 2 cos(x) - ex
for -6 x 3, and from this plot it appears that f(x) has three roots in this interval. The
bottom plot is a zoomed view near one of these roots, showing that f(x) has a root near
x = -1.454. Note the different vertical scale on this plot. Note also that when we zoom in
on this function it looks nearly linear over this short interval. This will be important when
we study numerical methods for approximating roots.
plot of 2cos(x) - exp(x)
5
0
-5
-10
-15
-20
-25
-6

-5

-4

-3

-2

-1

zoomed view
0.02

0.01

-0.01

-0.02
-1.46

-1.458 -1.456 -1.454

-1.452

-1.45

-1.448

-1.446 -1.444 -1.442

-1.44

a) Modify this script so that the bottom plot shows a zoomed view near the leftmost
root. Write an estimate of the value of this root to at least 3 decimal places. 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.
b) Edit the script from part (a) to plot the function
 

4    3
2  

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

Solution:
a) The root is approximately -4.717. The following code produces the plot below:
% Plot function over large interval.
subplot(2,1,1)
x = [-6:.01:3];
plot(x,2*cos(x)-exp(x))
title('plot of 2cos(x) - exp(x)')
% Zoom in on smaller interval about one root.
subplot(2,1,2)
xx = [-4.718:.0001:-4.716];
plot(xx,2*cos(xx)-exp(xx))
title('zoomed view')
plot of 2cos(x) - exp(x)
10
0
-10
-20
-30
-6

-5

-4

-3

-3

x 10

-2

-1

zoomed view

2
1
0
-1
-2
-4.718

-4.7178 -4.7176 -4.7174 -4.7172

-4.717

-4.7168 -4.7166 -4.7164 -4.7162

b) The root is approximately 0.933. The following code produces the plot below:
% Plot function over large interval.
subplot(2,1,1)
x = [0:.01:4];
plot(x, (4*x.*sin(x)-3)./(2 + x.^2))
title('plot of (4x sin(x) - 3)/(2 + x^2)')
% Zoom in on smaller interval about one root.
subplot(2,1,2)
xx = [.933:.0001:.934];
plot(xx, (4*xx.*sin(xx)-3)./(2 + xx.^2))
title('zoomed view')

-4.716

plot of (4x sin(x) - 3)/(2 + x 2)


1
0.5
0
-0.5
-1
-1.5

0.5

1.5

-3

1.5

2.5

3.5

zoomed view

x 10

1
0.5
0
-0.5
-1
0.933

0.9332

0.9334

0.9336

0.9338

0.934

0.9342

Problem 3 [9 points]:
In this exercise, you will plot initial stages of a process that creates a fractal known as
Koch's Snowake, which is depicted below.

This exercise uses the MATLAB M-file koch.m, which you will find on the web page. The
M-file contains all the necessary commands to create the fractal, except for the
necessary plotting commands. Edit this M-file so that each stage of the fractal is plotted.
(Hint: This can be accomplished by adding a plot command just before the completion
of the outer for loop.) Add the following commands to keep consistency between plots
in the animation:
axis([-0.75 0.75 -sqrt(3)/6 1]);
axis equal

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

Stage 1

Stage 2

0.8

0.8

0.6

0.6

0.4

0.4

0.2

0.2

-0.2

-0.2
-0.5

0.5

-0.5

Stage 3

0.5

Stage 4

0.8

0.8

0.6

0.6

0.4

0.4

0.2

0.2

-0.2

-0.2
-0.5

0.5

-0.5

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,
where each number occurs exactly once, and the sum of the entries of any row, any
column, or any main diagonal is the same. The MATLAB command magic(n) creates
an n by n (where n > 2) magic square. Create a 5 by 5 magic square and verify
using the sum command in MATLAB that the sum of the columns, rows and
diagonals are equal. Create a log of your session that records your work. (Hint: To
find the sum of the diagonals, read documentation for the diag and the flipud
commands.)
b) With the following matrices and vectors:

Compute the following both by hand and in Matlab. For the MatLab computations,
use the diary command to record your session.
a)
b)
c)
d)
e)
f)

v Tw
vwT
Av
A Tv
AB
BA

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, column 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,1) % Sum of each column


ans =
65

65

65

65

65

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

b)

Problem 5 [10 points]:


Computer graphics make extensive use of matrix operations. For example, rotating an
object is a simple matrix vector operation. In two dimensions, 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, let us rotate the rectangle with vertex coordinates (1, 0); (0, 1); (-1, 0);
and (0, -1) through an angle = /4. In MATLAB, type the following code to generate
the original and rotated squares plotted one on top of the other.
% create matrix whose columns contain the coordinates of each vertex.
U = [1 0 -1 0; 0 1 0 -1];
theta = pi/4;
% Create a red unit square
% Note U(1,:) denotes the first row of U
fill(U(1,:),U(2,:),'r')
% Retain current plot and axis properties so that
% subsequent graphing commands add to the existing graph

hold on
% Set the axis
axis([-2 2 -2 2]);
% Perform rotation.
R = [cos(theta) -sin(theta); sin(theta) cos(theta)];
V = R*U;
fill(V(1,:), V(2,:),'b');
axis equal tight, 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.
a) Adapt this code to plot a triangle with vertices (5, 0); (6, 2) and (4, 1). Plot the
triangles resulting from rotating the original triangle by /2, , and 3/2 radians
about the origin. Plot all four triangles on the same set of axes.
b) Rotating by radians and then rotating by - radians leaves the figure
unchanged. This corresponds to multiplying first by R() and then by R(-).
Using MATLAB, verify that these matrices are inverses of each other (that is,
their product is the identity) for = /3 and for = /4.
c) Using the trigonometric identities cos() = cos(-) and -sin() = sin(- ), prove
that R() and R(-) are inverses of each other for any .
d) Let R be the matrix that rotates counterclockwise through the angle /8, and let
#  0.9 & . Then the matrix # simultaneously rotates and shrinks an object. Edit
the code above to repeatedly rotate and shrink (by the same amounts on each
step) the square (again originally with coordinates (1, 0); (0, 1); (-1, 0); and (0,
-1) for 50 iterations. The plot should show all of the 51 squares on the same set
of axes.
e) Apply # but now after each rotation translate the square by 1 unit in the x
direction and 2 units in the y direction. Note, you must apply the rotation and
translation to all the vertices of the square. The resulting squares should visually
suggest the existence of a fixed point. Such a point satisfies the equation


1
' )  # ' )  ' ).
(
(
2
Solve this equation to find the numerical value of this fixed point.

Solution:
a) Following is the MATLAB code and the plot that it produces:
% Create matrix whose columns contain the coordinates of each vertex.
U = [5 6 4; 0 2 1];

theta = pi/2;
% Create a red triangle. Note U(1,:) denotes the first row of U.
fill(U(1,:),U(2,:),'r')
hold on
% Set the axis.
axis([-2 2 -2 2]);
for i=1:3,
% Rotate through angle pi/2 three times.
% Perform rotation.
R = [cos(theta) -sin(theta); sin(theta) cos(theta)];
U = R*U;
fill(U(1,:),U(2,:),'b') % Plot the rotated triangle.
end;
axis equal tight, grid
6

-2

-4

-6
-6

-4

-2

b) Following are the MATLAB commands (recorded using the diary command):
% Test if R(theta) and R(-theta) are inverses when
% theta = pi/3.
theta = pi/3;
R = [cos(theta) -sin(theta); sin(theta) cos(theta)];
Ri = [cos(-theta) -sin(-theta); sin(-theta) cos(-theta)];
R*Ri

ans =
1
0

0
1

% They are!
% Test if R(theta) and R(-theta) are inverses when
% theta = pi/4.
theta = pi/4;
R = [cos(theta) -sin(theta); sin(theta) cos(theta)];
Ri = [cos(-theta) -sin(-theta); 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; 0 1 0 -1];
theta = pi/8;
% Create a red unit square. Note U(1,:) denotes the first row of U.
fill(U(1,:),U(2,:),'r')
hold on
% Set the axis.
axis([-2 2 -2 2]);

% Perform rotations and shrinkings.


R = [cos(theta) -sin(theta); sin(theta) cos(theta)];
Rhat = .9*R;
for iter=1:50,
U = Rhat*U;
fill(U(1,:),U(2,:),'b');
end;
axis equal tight, grid on
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
-1

-0.5

0.5

e) The following code rotates, shrinks, and translates the square and produces the plot
below. It identifies the fixed point as (-3.5392,4.6351).
% Create matrix whose columns contain the coordinates of each vertex.
U = [1 0 -1 0; 0 1 0 -1];
theta = pi/8;
% Create a red unit square. Note U(1,:) denotes the first row of U.
fill(U(1,:),U(2,:),'r')
hold on

% Set the axis.


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

5
4
3

2
1
0

-1

fixedpt =
-3.5392
4.6351

-5

-4

-3

-2

-1

You might also like