You are on page 1of 9

   IT1005 

NATIONAL UNIVERSITY OF SINGAPORE 

SCHOOL OF COMPUTING 

QUIZ 2 FOR 
Semester 1 AY2012/2013 

IT1005 – Introduction to Programming with MATLAB 

30 Oct 2012        Time Allowed: 95 Minutes 

INSTRUCTIONS TO CANDIDATES: 

1. This examination paper contains FIVE (5) questions and comprises NINE (9) printed pages, 
including this page. The weightage for each question is as indicated, and total 50 marks. 
2. Answer ALL questions within the spaces/boxes provided in this booklet. 
3. This is an Open Book examination. 
4. You are allowed and encouraged to use calculator. 
However, any other form of electronic devices is NOT allowed to be used during examination. 
5. Please write your matriculation number below. Do NOT write your name. 

MATRICULATION NO: ________________________________ 

This portion is for examiner’s use only 

Question  Average Marks  Remarks 


Q1  8.09/10 Time differentiator question
Q2  6.57/10 Not related to ChBE 
Q3  6.04/10 Do NOT do this in actual experiment! 
Q4  ~8.13/10 (out of ~136 students) 
Q5  ~7.80/10 (out of ~136 students)
Total  ~36.63/50 (or ~73.26/100, ~7 points higher than Quiz 1) 
 
Note: Quiz 2 marks will be scaled to 25% 


 
   IT1005 

Question 1 – Lab Procurement (10 Marks)

A Chemistry lab technician of an NUS Chemical engineering lab has just procured some items: He
bought x binocular microscope, y distillation apparatus, z burners, and he spent A SGD in total.
This lab technician told you the following riddle: Buying x binocular microscopes actually cost the
same as his new laptop, which is B SGD. He also told you that buying 2y distillation apparatus and
x binocular microscopes costs the same as buying five new iPhone 5, which is C SGD per iPhone 5.
Based on some “GIYF searches”, you know that one binocular microscope like the one bought by
the lab technician is 600 SGD, one distillation apparatus is 80 SGD, and one burner is 45 SGD.

Left to right: Example of a binocular microscope, a distillation apparatus, and a burner


(Screenshots are taken from: http://www.hometrainingtools.com/lab‐equipment/c/65/)

a). Use the skill that you have learned in IT1005 to compute what is x, y, and z, if A = 4505 SGD,
B = 3000 SGD, and C = 824 SGD. Show all MATLAB commands that you need (4 marks).

This is just 3 unknowns in 3 linear equations; A clear Linear Algebra problem; best: use ‘\’, e.g. 
[45 80 600; 0 2*80 600; 0 0 600] \ [4505; 5*824; 3000]
z=ans(1), y=ans(2), x=ans(3) % note that [z y x] = A\b causes error
Note 1: fsolve solution will only get 3 marks (may not be the best/most accurate solver in
general). If you know that your system of equations is linear, use ‘\’ operator that does not ‘guess’!
Note 2: Please use proper MATLAB syntax for answering this question. 3 marks otherwise.

b). However, your laptop is just spoilt , thus you do not have access to MATLAB in your laptop…
You are so curious and want to compute x, y, z MANUALLY using an algorithm that you know…
Show the full working of the required steps to get the marks (6 marks).

For clever manual solution, we need to rearrange the variables in the equations (x, y, z) to (z, y, x) 
so that matrix A has lower triangular matrix all zeroes right from the start!!! 

45 * z + 80 * y + 600 * x = 4505
0 * z + 2*80 * y + 600 * x = 5*824
0 * z + 0 * y + 600 * x = 3000
So, x = 5 (from 3000/600)
And therefore, y = 7 (from (5*824 – 3000) / (2*80))
And finally, z = 21 (from (4505 – 3000 – 80*7) / 45)
This is doable in less than 3‐4 minutes . A full simulation of Gaussian Elimination using the order 
x, y, z as “implied” in the question will take ~15‐20 minutes (or more… depending on your speed).


 
   IT1005 

% you can use the entire page 3 if you need more space for question 1b
% make sure that your steps are as clear as possible

Actually, you do NOT need this page at all if you use clever manual solution above.
However, the full Gaussian Elimination steps using x, y, z ordering is shown below:

Initially:

600 80 45 | 4505
600 160 0 | 4120
600 0 0 | 3000

Eliminate x from row 2 and 3:

600 80 45 | 4505
0 80 -45 | -385
0 -80 -45 | -1505

Eliminate y from row 3:

600 80 45 | 4505
0 80 -45 | -385
0 0 -90 | -1890

Back substitution:
z = -1890 / -90 = 21
So:
y = (-385 + 45*21) / 80 = 560 / 80 = 7
Therefore:
x = (4505 - 80*7 - 45*21) / 600 = 3000 / 600 = 5

The marking scheme: 2 marks per correct variable value of x, y, z.


PS: If you get non-integer x/y/z, you should realize that your intermediate computation is wrong.
At least 1 mark for some effort in using Gaussian Elimination although all x, y, z are wrong.
0 mark for any form of MATLAB code here (you do NOT have laptop with MATLAB to run it).

Some rough statistics: About ~90% of the cohort got z = 21, y = 7, and x = 5 correctly.
About ~50% do not use this blank box in page 3 (the quick method, creative thinking (or luck)).
About ~50% write a lot in this blank box in page 3 (the standard method as taught in class).


 
   IT1005 

Question 2 – Happy First Birthday Jane (10 Marks)

Steven wants to give a memorable birthday present to his one year old daughter: Jane Angelina Halim
(24 October 2011-12). Last year, he told IT1005 students about his savings plan for Jane’s education needs
(which is still ongoing!). This year, he wants to give Jane a MATLAB cake as shown below.

Your task is to write several MATLAB User-Defined Functions to compose the cake.
This task has nothing to do with ChBE, but be a good student and create a birthday cake for Jane!

a). Function DrawCircle takes in three parameters, x, y, and r from user and returns nothing.
It then plots a red circle centered at coordinate (x, y) with radius r. Write this function below (2 marks).

function DrawCircle(x, y, r)
plot(x + r * sin(0:0.1:2*pi), y + r * cos(0:0.1:2*pi), 'r');
% already shown in Lecture 06 & lab 05
% marking scheme: 0 (blank or deemed as blank), 1 (wrong),
% or 2 (fully correct) marks => axis equal is marked in Q2c.
% common mistakes:
% -forgot to use red color for the circle border
% -wrong circle equation formula
% -forgot to shift the circle to be centered at (x,y)

b). Function DrawLine takes in four parameters x1, y1, x2, and y2 from user and returns nothing.
It then plots a blue line from (x1, y1) to (x2, y2). Write this function below (2 marks).

function DrawLine(x1, y1, x2, y2)


plot([x1 x2], [y1 y2]); % short and sweet
% note that the default color is already blue
% marking scheme: 0 (blank or deemed as blank), 1 (wrong),
% or 2 (correct) marks
% common mistakes:
% -plot(x1:x2, y1:y2); % vector size mismatch most of the time
% -use line equation formula % what if x1=x2, s.t. gradient=inf?
% (note that all candles are vertical lines!)


 
   IT1005 

c). Function DrawCake takes in one parameter age from user and returns nothing.
It then plots one big circle centered at coordinate (0, 0) with radius 3 units, then plots age copies of
“candles”. A candle is a combination of a straight line with 2 units of height plus a small ‘fire’ which is a
circle centered at the top of the line with radius 0.2 units. The base of a candle must be placed randomly
within the cake (i.e. the base of the candle must be strictly inside a circle centered at coordinate (0, 0)
with radius 3 units). It is OK for two candles to accidentally overlap (or too near to another candle) because
of random placement. Finally, write ‘Happy Xst/nd/th Birthday Jane’ as the title of the plot, but replace X
with age. See the screen shots below for DrawCake(3) and DrawCake(7).

Write this function below (6 marks).

function DrawCake(age)
clf; % not graded, but important for several calls of DrawCake
hold on; % two important steps, 1 mark if both steps exist
axis equal; % (this can also be written in Q2a)
DrawCircle(0, 0, 3); % call this, 1 easy mark
for i = 1:age % repeat 'age' times, 1 mark
x = 3; y = 3; % 1 mark for getting random (x, y) correctly
while x * x + y * y >= 9 % if outside circle (the cake)?
x = rand() * 6 - 3; y = rand() * 6 - 3; % try again
end
% SIMPLER ANSWER: you can just do this (not that 'random')
% x = rand(); y = rand();
% (x, y) will be a random coordinate between (0, 0) and (1, 1)
% which is guaranteed to be inside the cake ALL THE TIME!
% Other alternative, put the candles randomly around
% a smaller circle inside the cake
% angle = rand() * 2 * pi; % same angle for x and y
% x = 2 * sin(angle); y = 2 * cos(angle);

% draw the candle, 1 mark


DrawLine(x, y, x, y + 2); % height 2
DrawCircle(x, y + 2, 0.2); % put fire on top of the candle
end
% title with sprintf, 1 mark
title(sprintf('Happy %dst/nd/th Birthday Jane', age));


 
   IT1005 

Question 3 – Remove One Outlier… (10 Marks)

You have just done a chemistry experiment in module CNABCD and got the “Quantity (Q) versus time (h)”
data stored in a 1D row vector named as result. This data is obtained after length(result) hours in
lab, one data point per hour. Your CNABCD lecturer told you that if the experiment is conducted perfectly,
you should get a linear fit: Q = A*t + B, where A and B are two constants. However, you were a bit sloppy
and your data looks like the figure below if plotted (example with 7 data points or 7 hours of experiment).

You immediately realize that you have done a serious measurement error on the 6th hour.
If you ‘delete’ the 6th data point, you will get a much better linear fit: Q = 2*t + 0, which is shown below:
(DISCLAIMER: DO NOT DO THIS IN YOUR ACTUAL CHEMISTRY EXPERIMENT!)

Your task is write a User Defined Function DetectOutlier that takes in a row vector result as defined above
and returns one number, the index of an element in row vector result which removal improves the linear fit of
row vector result in the most significant manner. You can only delete exactly one data point. It is guaranteed
that there is exactly one clear outlier in all test data used in this question.

You can use MATLAB’s polyfit as shown in lab08. The help message of polyfit is shown below.

P = POLYFIT(X, Y, N) finds the coefficients of a polynomial P(X) of degree N that fits the data Y
best in a least-squares sense. P is a row vector of length N+1 containing the polynomial coefficients in
descending powers, P(1)*X^N + P(2)*X^(N-1) + … + P(N)*X + P(N+1).


 
   IT1005 

Some sample runs of this function:

>> DetectOutlier([2 4 6 8 10 15 14]) % as shown above


ans = 6
>> DetectOutlier([2 4 6 8 11 12 14]) % delete index 5 (11)
ans = 5
>> DetectOutlier([2 7 6 8 10 12 14]) % delete index 2 (7)
ans = 2
>> % it is better to delete index 2 (7) than to delete index 4 (9)
>> DetectOutlier([2 7 6 9 10 12 14])
ans = 2

Write your answer below (10 marks).

% 3 more test cases other than the 4 listed above (unique answer):
% >> DetectOutlier([9 8 7 6 5 4 1])
% ans = 7, Q = -1*t + 10, to break notion that Q is always 2*t + 0
% >> DetectOutlier([1 1000 1 1 1 1 1 1 1 1]) % result = 1x10!!
% ans = 2, Q = 0*t + 1, to break notion that Q must have a gradient
% >> DetectOutlier([1050 3001 4999 7002 9001 10999 12999 15001])
% ans = 1, Q ~= 1999*t - 999, large gradient/coefficient, imprecise

% shortest answer for these 7 test cases:


function i = DetectOutlier(result) % 1 mark
t = 1:length(result);
p = polyfit(t, result, 1); % 4 marks, -1 for any spotted mistake
% e.g. the parameters must be ordered correctly, the third
% parameter must be degree N = 1, return variable is OK, etc
[m i] = max(abs(p(1) .* t + p(2) – result)); % 5 marks, -1/mistake
% compare the linear fit at the same time point with vector result
% find an index which is very different with the linear fit
% or use:
% [m i] = max(abs(polyval(p, t) – result)); % same as above
% Common mistake:
% - i = find(max(abs(polyval(p, t) – result)));
% the answer is always 1
% - forgot to put . in .* in the third line above

% other (better) solutions exist and will be graded accordingly


% as long as it passes the 7 test data above, it will get 10 marks


 
   IT1005 

Question 4 - Fly Fly Away (10 Marks)

The total drag force on an airplane wing can be estimated as:

0.95 W 
2
D  0.01V 2   
Friction  V 
Lift

where D = drag force,  = ratio of air density between flight altitude and sea level, W = weight, and V =
velocity. The two factors, ‘friction drag’ and ‘lift’ contributing to drag in the above formula are affected
differently as velocity increases; friction drag increases with velocity, while the drag due to lift decreases. The
combination of the two factors leads to a minimum drag.

(a) If  = 0.6 and W = 16,000, use MATLAB to determine the minimum drag and the velocity at
which it occurs. Write down all the code/commands you need clearly (4 marks).

function D = drag(V, W) % the W is for part b later


rho = 0.6; % it is better to put these constants separately
D = 0.01 * rho * V ^ 2 + 0.95 / rho * (W / V) ^ 2;
------------------------------------------------------------------------

% In Command Window
[v_for_mindrag mindrag] = fminsearch(@(V) drag(V, 16000), 1)

% Alternative one liner answer:


[v_for_mindrag mindrag] = fminsearch(@(V) 0.01 * 0.6 * V ^ 2 + ...
0.95 / 0.6 * (16000 / V) ^ 2, 1)

% Using the given values, v_for_mindrag ~= 510 and mindrag ~= 3119

(b) How does this minimum vary in the range of W = 12,000 to 20,000 with  = 0.6? Use MATLAB to
answer this question, by plotting the minimum drag versus W in the above range. Write down all
MATLAB code you would need to do this. Make any assumptions that you deem fit, and state them
clearly (6 marks).

% Assume that the increment is +10


W = 12000:10:20000;
minD = zeros(1, length(W));
for i = 1:length(W)
minD(i) = fminsearch(@(V)drag(V, W(i)), 1);
end

plot(W, minD); % the plot is roughly a linear line


xlabel('W');
ylabel('min drag');
title('Min Drag vs W');


 
   IT1005 

Question 5 – CN5020/6020 – Advanced Reaction Engineering (10 marks)

Students in CN5020/6020 (Advanced Reaction Engineering) studied energy balances in non-isothermal


chemical reactors last week.

The expression for the temperature T of a non-isothermal stirred tank reactor for a simple exothermic reaction
A  B is given by the solution to the following equation:

k C P
0 C Af H  (T f T )
1 k 
where CAf = feed concentration of A, H = heat of reaction,  = density of reaction mixture, CP = specific heat
of reaction mixture and Tf = feed temperature, all of which are given to you as parameters in the problem. The
reaction rate constant k can be written as k = k0 exp(-E/RT) where you are given the values of activation
energy E, universal gas constant R and pre-activation factor k0.

The given information is:


CAf = 2000 mol/m3, H = - 25 kJ/mol,  = 1000 kg/m3, CP = 4.2 kJ/kg.K, Tf = 300 K, E = -10 kJ/mol, R =
8.314 J/mol.K and k0 = 103.

You are required to help a CN5020 student to plot the operating temperature of the reactor T, as a function of
residence time  in the range of 100 s to 2500 s. How would you use your MATLAB expertise to do that?

function ret = q5(T, tau)


% copy paste all the known values
Caf = 2000;
dH = -25;
rho = 1000;
Cp = 4.2;
Tf = 300;
E = -10;
R = 8.314 / 1000; % note that R is in J/mol.K initially, we want KJ/mol.K
k0 = 1000;
k = k0 * exp(-E / (R * T));
ret = –k / (1 + k * tau) * Caf * dH + rho * Cp / tau * (Tf - T);
------------------------------------------------------------------------

% In Command Window, assume tau is of increment of +10


tau = 100:10:2500;
temp = zeros(1, length(tau));
for i = 1:length(tau)
temp(i) = fsolve(@(T) q5(T, tau(i)), 273); % most likely around 273 K
end

plot(tau, temp); % the answer is around 273 K


xlabel('Residence time tau t');
ylabel('Operating Temperature T');
title('T vs t');

End of Paper . All the best .


 

You might also like