0% found this document useful (0 votes)
6 views14 pages

Test2C Solution

The document provides suggested solutions for a MATLAB laboratory test, covering various mathematical problems including symbolic summation, differential equations, image processing, polar decomposition, and ellipse geometry. Each section includes MATLAB commands and expected outputs for tasks such as plotting, saving data, and calculating distances. The solutions demonstrate the application of MATLAB functions and techniques to solve mathematical and computational problems effectively.

Uploaded by

0715 hky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views14 pages

Test2C Solution

The document provides suggested solutions for a MATLAB laboratory test, covering various mathematical problems including symbolic summation, differential equations, image processing, polar decomposition, and ellipse geometry. Each section includes MATLAB commands and expected outputs for tasks such as plotting, saving data, and calculating distances. The solutions demonstrate the application of MATLAB functions and techniques to solve mathematical and computational problems effectively.

Uploaded by

0715 hky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

THE CHINESE UNIVERSITY OF HONG KONG

Department of Mathematics
2024-25 Term 2 MATH2221C Mathematics Laboratory II
Test 2 Suggested Solutions

• Full Mark: 60

1. Use the MATLAB Symbolic Math Toolbox to solve the following problems. Write
down both the MATLAB commands and the answers obtained in the box below.
n
X
(a) (4 marks) Find (n2 − n − 1 + 2k) and simplify the answer.
k=1

Solution:
syms n k
S = symsum(nˆ2-n-1+2*k,k,1,n);
simplify(S)

The answer is n3 .

(b) (4 marks) Find the one-sided limit lim (tan x)−1/cos x .


x→(π/2)−

Solution:
syms x
limit(tan(x)ˆ(-1/cos(x)),x,pi/2,'left')

The answer is 0.
 2
exp(cx)
(c) (4 marks) Let a be a constant and f (x) = . Find f ′ (x).
x

Solution:
syms x c
diff((exp(c*x)/x)ˆ2,x)

2c exp(2cx) 2 exp(2cx)
The answer is − .
x2 x3

Run the MATLAB command clearvars to clear all variables in the workspace before
moving on to the next question.
2

2. Let y(t) be a differentiable function satisfying the following differential equation:

y ′ (t) = t2 y exp(−y) + sin(y) + 1,

with the initial condition y(0) = 0.

(a) (5 marks) Write a MATLAB function q2a.m to do the following:

• Use [t,y] = ode45(...) to solve the above differential equation in the time
interval tspan = [0,10].
• Create a MATLAB figure to plot the values of y versus t using red solid lines.
• Also, save the variables t and y in a .mat file named myode.mat.

Solution:
odefun = @(t,y) tˆ2*y*exp(-y)+sin(y)+1;
[t,y] = ode45(odefun, [0,10], 0);
figure;
plot(t,y,'r-');
save('myode.mat','t','y');

The figure is as follows:


3

(b) (5 marks) Write a MATLAB function q2b.m to do the following:

• Clear all variables in your MATLAB workspace using clearvars.


• Load the variables t and y from the file myode.mat into your workspace.
• Use the trapezoidal method to evaluate the integral
Z 10
I= y(t) dt
0

based on the vectors t and y.


• Display the value of I.

Solution:
clearvars;
load('myode.mat','t','y');
I = trapz(t,y);
disp(I);

The answer is 60.9588.

3. Consider a built-in image cameraman.tif (with size 256 × 256) in MATLAB:

(a) (5 marks) Write a MATLAB script q3a.m to do the following:

• Read cameraman.tif and denote it as I.


• It turns out that the cameraman has a twin brother, who is also a cameraman.
Create a new image J as shown below, which combines I and a flipped version
of it (Hint: you may use the function fliplr).
4

• Create a MATLAB figure and display the new image J.

• Also, save the combined image as twins.png.

Solution:
I = imread('cameraman.tif');
J = [I,fliplr(I)];
figure;
imshow(J);
imwrite(J,'twins.png');

The figure is as shown above.

(b) (5 marks) Write a MATLAB script q3b.m to do the following:

• Create a video file named looping twins.mp4 with the MPEG-4 format.
Denote the VideoWriter object as v.

• Set the frame rate of the video as 50 using v.FrameRate = 50;.

• Open the video file using open(v).

• Read twins.png and denote it as J.

• For i = 1, . . . , 512, do the following:

– Create a transformed image K = J(:,[i:512,1:(i-1)]);.

– Write the transformed image K to the video.

• Finally, close the video file using close(v).


5

Solution:
v = VideoWriter('looping twins.mp4', 'MPEG-4');
v.FrameRate = 50;
open(v);
J = imread('twins.png');
for i = 1:512
K = J(:,[i:512,1:(i-1)]);
writeVideo(v,K);
end
close(v);

4. Let A be an n × n real invertible matrix with the singular value decomposition


A = U SV T .

By defining Q = U V T and P = V SV T , we have a new matrix factorization method


(also known as the polar decomposition):

A = QP.

(a) (5 points) Write a MATLAB function [Q,P] = polar decomposition(A) that


takes a square matrix A as input and returns the two matrices Q and P as
described in the method above.

As a test case, if A = [1,2,3;4,5,6;3,1,4], we should be able to get:


    
1 2 3 −0.6272 0.1640 0.7614 3.1743 1.8707 3.5249
    
= 3.9343 3.3199 .
    
4 5 6  0.5067 0.8284 0.2389 1.8707
    
3 1 4 0.5916 −0.5356 0.6026 3.5249 3.3199 6.1281

Solution:
function [Q,P] = polar decomposition(A)
[U,S,V] = svd(A);
Q = U*V';
P = V*S*V';
end
6

(b) (5 points) Theoretically, it is easy to prove that in the polar decomposition A = QP


described above, the resulting Q is an orthogonal matrix (with QT Q = I) and P is
a symmetric matrix (with P T = P ). Here, we check whether the properties are
satisfied numerically.
Write a MATLAB script q4b.m to create a 50 × 6 cell array C:

• The first row of C consists of six character arrays:


‘A’, ‘Q’, ‘P’, ‘Decomposition Error’, ‘Orthogonality Error’, ‘Symmetry Error’.
• For n = 2, 3, . . . , 50, store the following matrices/scalars in the six cells of the
n-th row of C accordingly:
(1) An n × n matrix A constructed using A = magic(n) + rand(n), where
magic is the built-in function for generating a magic square matrix and
rand generates a random matrix.
(2) The matrix Q obtained by polar decomposition(A).
(3) The matrix P obtained by polar decomposition(A).
(4) The decomposition error ∥A − QP ∥2 .
(5) The orthogonality error ∥QT Q − In ∥2 , where In is the n × n identity matrix.
(6) The symmetry error ∥P T − P ∥2 .

Solution:
C = cell(50,6);
C{1,1} = 'A';
C{1,2} = 'Q';
C{1,3} = 'P';
C{1,4} = 'Decomposition Error';
C{1,5} = 'Orthogonality Error';
C{1,6} = 'Symmetry Error';
for n = 2:50
A = magic(n) + rand(n);
[Q,P] = polar decomposition(A);
C{n,1} = A;
C{n,2} = Q;
C{n,3} = P;
C{n,4} = norm(A-Q*P,2);
7

C{n,5} = norm(Q'*Q-eye(n),2);
C{n,6} = norm(P'-P,2);
end

5. Note that any ellipse E in R2 can be represented by the parametric equation:


      
x(t) x cos θ − sin θ a cos t
  =  0 +   , (1)
y(t) y0 sin θ cos θ b sin t

where

• (x0 , y0 ) ∈ R2 is the center of the ellipse E.

• a, b ∈ R+ are the lengths of the semi-axes of E.

• θ ∈ [0, 2π) represents the rotation angle of E.

• t is a real parameter.

(a) (5 marks) Write a MATLAB function [x,y] = make ellipse(parameter) with


the following inputs and outputs:

• parameter is a structure array with fields x0, y0, a, b, theta storing the
corresponding parameters x0 , y0 , a, b, θ of the ellipse E in Eq. (1).

• x, y are function handles (x = @(t)... and y = @(t)...) representing the


x- and y-coordinates of the points on E as described in Eq. (1).

Different inputs will be used to test your code.

As a test case, if we set parameter based on (x0 , y0 , a, b, θ) = (−5, 1, 4, 2, 4π/7),


the resulting x,y together with the following plotting commands should give the
figure on the right-hand side:
8

[x,y] = make ellipse(parameter);


figure;
t = linspace(0,2*pi,100);
plot(x(t),y(t),'b-');
axis equal;

Solution:
function [x,y] = make ellipse(parameter)
x0 = parameter.x0;
y0 = parameter.y0;
a = parameter.a;
b = parameter.b;
theta = parameter.theta;
x = @(t) x0 + [cos(theta), -sin(theta)]*[a*cos(t); b*sin(t)];
y = @(t) y0 + [sin(theta), cos(theta)]*[a*cos(t); b*sin(t)];
end

(b) (6 marks) Write a MATLAB function


[d,px,py,qx,qy] = min distance(parameter1,parameter2) to find the mini-
mum Euclidean distance between any two given ellipses E1 , E2 . More specifically:

• The two inputs parameter1 and parameter2 are two structure arrays with
fields x0, y0, a, b, theta. Each input stores the parameters x0 , y0 , a, b, θ for
representing an ellipse (E1 or E2 ) based on Eq. (1).

• The output d is the minimum Euclidean distance between E1 and E2 .

• For the remaining outputs, (px,py) and (qx,qy) are the coordinates of two
points on E1 and E2 respectively at which the minimum Euclidean distance d
is attained.

• Additionally, the function should create a MATLAB figure to plot the two
ellipses E1 , E2 using blue solid lines. On the same plot, also plot the two points
(px,py) and (qx,qy) using red circle markers with red marker face colors and
draw a red solid line to connect them, and set equal axis scales.
9

Different inputs will be used to test your code.

As a test case, if (x0 , y0 , a, b, θ) = (−5, 1, 4, 2, 4π/7) for E1 and (5, 8, 5, 4, π/4) for
E2 , we should have d = 5.0037, px = −3.6303, py = 3.0948, qx = 0.8511,
qy = 5.3206, and the resulting figure should be as follows:

Solution:
function [d,px,py,qx,qy] = min distance(parameter1,parameter2)

[x1,y1] = make ellipse(parameter1);


[x2,y2] = make ellipse(parameter2);

% We can either minimize the distance or the squared distance


% fun = @(t) sqrt((x1(t(1))-x2(t(2)))ˆ2 + (y1(t(1))-y2(t(2)))ˆ2);
fun = @(t) (x1(t(1))-x2(t(2)))ˆ2 + (y1(t(1))-y2(t(2)))ˆ2;
t0 = [0;0];
[t opt,fun opt] = fminunc(fun,t0);

% d = fun opt; % if we choose to minimize the distance directly


d = sqrt(fun opt); % if we choose to minimize the squared distance
px = x1(t opt(1));
py = y1(t opt(1));
qx = x2(t opt(2));
10

qy = y2(t opt(2));

% make the plot


figure;
t = linspace(0,2*pi,100);
plot(x1(t),y1(t),'b-');
hold on;
plot(x2(t),y2(t),'b-');
plot([px,qx],[py,qy],'ro-','MarkerFaceColor','r');
axis equal
end

Some of the test inputs and the resulting figures:


parameter1 = struct('x0',-5,'y0',1,'a',4,'b',2,'theta',4*pi/7);
parameter2 = struct('x0',5,'y0',8,'a',5,'b',4,'theta',pi/4);
parameter3 = struct('x0',5,'y0',-4,'a',1,'b',3,'theta',5*pi/3);
parameter4 = struct('x0',0,'y0',0,'a',8,'b',2,'theta',-pi/4);
11

(c) (7 marks) Write a MATLAB function L = max perimeter(parameter1,parameter2)


to find four points A, B, C, D, where A, B ∈ E1 and C, D ∈ E2 (E1 , E2 are two given
ellipses), such that the perimeter of the quadrilateral formed by the four points is
maximized. More specifically:

• The two inputs parameter1 and parameter2 are structure arrays storing the
parameters of two ellipses E1 , E2 in the same format as in part (b).

• The output L is the maximum perimeter.

• Additionally, the function should create a MATLAB figure to plot the two
ellipses E1 , E2 using blue solid lines and the resulting quadrilateral with max-
imum perimeter using red solid lines and red circle markers with red marker
face colors, and set equal axis scales.

Different inputs will be used to test your code.

As a test case, if (x0 , y0 , a, b, θ) = (−5, 1, 4, 2, 4π/7) for E1 and (5, 8, 5, 4, π/4) for
E2 , we should have L = 46.2048, and the resulting figure should be as follows:
12

Solution:
Some remarks:

• The perimeter of a quadrilateral ABCD is the total length of AB, BC,


CD, DA.
• Maximizing the perimeter is equivalent to minimizing −(perimeter).
• If we directly use fminunc to minimize −(perimeter), sometimes we may
obtain a “flipped” quadrilateral (i.e. the edges BC and AD intersect),
as that naturally gives longer edge lengths. However, in this case, the
points do not form a valid quadrilateral. Therefore, we use fmincon with
a constraint to prevent such flips.

function L = max perimeter(parameter1,parameter2)

[x1,y1] = make ellipse(parameter1);


[x2,y2] = make ellipse(parameter2);

% t1, t2: correspond to two points in E 1


% t3, t4: correspond to two points in E 2
L12 = @(t) sqrt((x1(t(1))-x1(t(2)))ˆ2 + (y1(t(1))-y1(t(2)))ˆ2);
L23 = @(t) sqrt((x1(t(2))-x2(t(3)))ˆ2 + (y1(t(2))-y2(t(3)))ˆ2);
L34 = @(t) sqrt((x2(t(3))-x2(t(4)))ˆ2 + (y2(t(3))-y2(t(4)))ˆ2);
L41 = @(t) sqrt((x2(t(4))-x1(t(1)))ˆ2 + (y2(t(4))-y1(t(1)))ˆ2);
fun = @(t) -(L12(t)+L23(t)+L34(t)+L41(t)); % -(perimeter)
t0 = [0;pi;0;pi];
[t opt,fun opt] = fmincon(fun,t0,[],[],[],[],[],[], ...
@(t)noflipconstraint(t,x1,x2,y1,y2));
L = -fun opt;
px = x1(t opt(1));
py = y1(t opt(1));
qx = x1(t opt(2));
qy = y1(t opt(2));
rx = x2(t opt(3));
ry = y2(t opt(3));
sx = x2(t opt(4));
sy = y2(t opt(4));
13

figure;
t = linspace(0,2*pi,100);
plot(x1(t),y1(t),'b-');
hold on;
plot(x2(t),y2(t),'b-');
plot([px,qx,rx,sx,px],[py,qy,ry,sy,py],'ro-', ...
'MarkerFaceColor','r');
axis equal
end

function [c, ceq] = noflipconstraint(t,x1,x2,y1,y2)


% Use cross product to determine whether there is any flipping
AB = [x1(t(2))-x1(t(1)), y1(t(2))-y1(t(1)), 0];
BA = -AB;
BC = [x2(t(3))-x1(t(2)), y2(t(3))-y1(t(2)), 0];
CB = -BC;
CD = [x2(t(4))-x2(t(3)), y2(t(4))-y2(t(3)), 0];
DC = -CD;
DA = [x1(t(1))-x2(t(4)), y1(t(1))-y2(t(4)), 0];
AD = -DA;
N1 = cross(AD,AB); % for the angle DAB
N2 = cross(BA,BC); % for the angle ABC
N3 = cross(CB,CD); % for the angle BCD
N4 = cross(DC,DA); % for the angle CDA
c = [N1(3), N2(3), N3(3), N4(3)]; % want all to be <= 0
ceq = []; % equality constraints are not needed
end

Some of the test inputs and the resulting figures:


parameter1 = struct('x0',-5,'y0',1,'a',4,'b',2,'theta',4*pi/7);
parameter2 = struct('x0',5,'y0',8,'a',5,'b',4,'theta',pi/4);
parameter3 = struct('x0',5,'y0',-4,'a',1,'b',3,'theta',5*pi/3);
parameter4 = struct('x0',0,'y0',0,'a',8,'b',2,'theta',-pi/4);
parameter5 = struct('x0',0,'y0',5,'a',4,'b',2,'theta',5*pi/7);
parameter6 = struct('x0',5,'y0',8,'a',5,'b',4,'theta',pi/4);
14

Some other random inputs were also used, for example:

⃝ △ □ End of Test ⃝ △□

You might also like