IT1005

advertisement
Lab session on week 9 (5th meeting)
IT1005
Good Friday and Happy Easter to all students,
especially for those who understand the meaning and celebrate these events .
Since Friday is a public holiday, students with lab sessions on Friday are advised
to attend parallel lab sessions on the other days!
Lab 5 – Quick Check
• Have you all received my reply for lab 5?
– My reply should contains:
• Your M files
– Check your files for my comments, look for this tag “SH7: bla bla bla”.
– Use CTRL+F (Find feature) of your text editor to quickly identify my SH7 tags.
• Your Microsoft Word file
–
–
–
–
Only if you do not give me your M files.
Most of my comments will be in the M files.
Anyway, check my comments here, if any, especially for q1.c and q2.b.
IMPORTANT: PLEASE DO NOT SEND ME DUPLICATE STUFFS!
IF YOU SEND M FILES, DO NOT COPY THE CODE TO MS WORD FILE!
• Your marks is stored in the file “Marks.txt” inside the returned zip file!
– If there is something wrong with the marks, clarify it with me.
– Either under counting or over counting.
– I have been quite lenient in the past few labs, next time I will be stricter.
L5.Q1.a: my_mean (standard)
function theMean = my_mean(x) % let us name the input array as x.
% if you want to explain something about this function, here is the best place!
theSum = 0; % do not use name sum, as it is a default Matlab function name
n = numel(x);
for index = 1:n % sum everything from index 1 to last (note: there are other ways to do this loop)
theSum = theSum + x(index);
end
theMean = theSum / n; % return the average a.k.a. mean
% Notice that we suppress ALL intermediate outputs with ;!
% Our function should be clean!
L5.Q1.a: my_mean (geek)
function theMean = my_mean(x)
theMean = sum(x(:)') / numel(x);
% x(:) will give me an enumeration of the input array x (whatever dimension) into column vector
% Doing x(:)' will definitely give me a row vector
% Thus, this trick will work for array of ANY dimension =)
% sum will then work for this row vector.
% Note that there is this line in the lab 5 question 1.a.
% You are NOT ALLOWED to use the MATLAB mean command,
% and should instead use loops, etc (Matlab function sum is ok) to implement your function.
% Very short, eh =)...
L5.Q1.b: my_var (standard)
function theVar = my_var(x)
% We should just call our my_mean function here. Do not create it again (redundant!).
% Store the result in a variable so that we do not re-count mean every time! (Important!)
theMean = my_mean(x);
n = numel(x);
sumOfSD = 0; % sum of squared deviation!
for index = 1:n % accumulate the sum of squared deviation
sumOfSD = sumOfSD + (x(index) - theMean)^2;
end
theVar = sumOfSD / (n-1); % you know why we divide this with n-1 right?
L5.Q1.b: my_var (geek)
function theVar = my_var(x)
theVar = sum((x(:)' - my_mean(x)) .^ 2) / (numel(x) - 1);
% If you do not understand why that works, see these:
% 1. Convert input array x into a row vector ==> x(:)'
% 2. Find the difference with the mean, scalar expansion! ==> x(:)' - my_mean(x)
% 3. Square the differences ==> (x(:)' - my_mean(x)) .^ 2
% 4. Sum the squared differences ==> sum(result of part 3 above)
% 5. Divide the result in step 4 above with n – 1
L5.Q1.c: (Crazy) Testing
% Many ways to do this, as long as you can show that your program is correct.
% My way: There are mean and var commands in Matlab, let us compare with them THOROUGHLY!
% mean and var(iance) are floating points, we must use floating point comparison!
% Tests with MANY inputs, the best is to use random function :D, thorough test with minimum work
for test = 1:100 % can increase this if you want :p, this is called stress test in Software Engineering
A = randn(1,100); % just generate a big random array, every time the array is different
result1 = abs(my_mean(A) - mean(A(:)) < eps); % CANNOT just say my_mean(A) - mean(A(:)) !
result2 = abs(my_var(A) - var(A(:)) < eps); % We MUST test the ABSOLUTE difference!
if result1 ~= 1 || result2 ~= 1
disp(sprintf('Test %d: WARNING, your program is still WRONG!', test));
else
disp(sprintf('Test %d: OK', test));
end
end
L5.Q1.d: Using randn
length = input('Enter the length of the random normalized array: ');
arr = randn(1,length); % Random row array with mean near 0, variance near 1!
theMean = my_mean(arr);
theVar = my_var(arr);
% Since the question wants the 'ans =' to be printed, I use sprintf here!
sprintf('The actual mean is %g and the actual variance is %g. Therefore the mean is off by %g, and the variance is off by %g.', ...
theMean, theVar, abs(theMean), abs(theVar-1.0)) % Do not write ; here!
% for mean, you do not need to say abs(theMean-0), the -0 part is redundant
L5.Q2.a: my_sort.m (standard)
function d = my_sort(x) % assume the input array x is a row vector
d = x; % copy x to d first, d is the variable that holds our answer!
n = numel(x);
% as mentioned in lab hint... no change at all...
for i = 1:n
for j = 1:(n-1)
if d(j) > d(j+1)
tmp = d(j); % need to store this in a temporary variable first
d(j) = d(j+1); % otherwise the value of d(j) is gone after we run this line!
d(j+1) = tmp;
end
end
end
% no need to say some returnVariable = d, since d is already sorted when loop stop! So just return d!
L5.Q2.a: my_sort.m (better)
function d = my_sort(x) % assume the input array x is a row vector
d = x; % copy x to d first, d is the variable that holds our answer!
for i=numel(x):-1:1 % notice that this loop is decreasing now
changed = 0; % assume nothing is swapped before entering the inner loop below
for j = 1:(i-1) % we can actually stop when j is already i-1!, and remember that i is decreasing!
if d(j) > d(j+1)
tmp = d(j);
d(j) = d(j+1);
d(j+1) = tmp;
changed = 1; % something is still swapped, set this changed flag to 1!
end
end
if changed == 0 % do Google search on the term bubble sort to learn about this enhancement!
break; % stop the bubble sort as soon as you do not see any more swap in an iteration!
end
end
L5.Q2.b: (Crazy) Testing
% Many ways to do this, as long as you can show that your program is correct.
% My way: generate many random arrays, compare my_sort with Matlab default sort!
% Tests with MANY inputs, the best is to use random function :D, thorough test with minimum work
for test = 1:100 % can increase this if you want :p, this is called stress test in Software Engineering
A = rand(1,100); % just generate a big random array, every time the array is different
result = all(my_sort(A) == sort(A)); % check if every single element after sorting is the same!
% alternatively, you can say result = isequal(my_sort(A), sort(A));
% you can also create a test to check whether the elements in A keeps increasing from left to right!
if result ~= 1
disp(sprintf('Test %d: WARNING, your program is still WRONG!', test));
else
disp(sprintf('Test %d: OK', test));
end
end
L5.Q2.c: my_sort2.m (better)
function d = my_sort2(x, asc) % now you have TWO arguments!
d = x;
for i=numel(x):-1:1
changed = 0;
for j = 1:(i-1)
if (asc == 1 & d(j) > d(j+1)) | (asc ~= 1 & d(j) < d(j+1)) % the only tweak to sort descending!
tmp = d(j);
d(j) = d(j+1);
d(j+1) = tmp;
changed = 1;
end
end
if changed == 0
break;
end
end
L5.Q2.c: my_sort2.m (geek)
function d = my_sort2(x, asc)
d = my_sort(x); % call our standard ascending sort, if asc == 1, nothing else will happen.
if asc ~= 1 % if user wants descending
d = fliplr(d); % just reverse it :)
end
L5.Q2.d: Application
length = 0;
while length < 1
length = input('Enter the length (>0) of the random array: '); % this time, no need to use randn!
end
asc = -1; % assume 1 = ascending, 0 = descending
while ~(asc == 1 || asc == 0) % keep asking when the input is not 1 nor 0!
asc = input('Sort ascending (1) or descending (0): ');
end
before = rand(1,length) % Random array, elements from [0.0-1.0], ; omitted so array is printed!
after = my_sort2(before, asc) % I do not use ; so that the sorted array is immediately printed.
The Art of White Spacing
•
•
•
•
White space = blank lines.
Used to separate (or group) ‘logical blocks’ of code.
So that we can see that blocks in a glance!
Let’s see the following examples:
The Art of White Spacing (Bad)
function d = my_sort(x) % assume the input array x is a row vector
d = x; % copy x to d first, d is the variable that holds our answer!
for i=numel(x):-1:1 % notice that this loop is decreasing now
changed = 0;
for j = 1:(i-1) % we can actually stop when j is already i-1!, and remember that i is decreasing!
if d(j) > d(j+1)
tmp = d(j);
d(j) = d(j+1);
d(j+1) = tmp;
changed = 1; % something is still swapped
end
end
if changed == 0 % do Google search on the term bubble sort to learn about this enhancement!
break; % stop the bubble sort as soon as you do not see any more swap in an iteration!
end
end
The Art of White Spacing (Bad)
function d = my_sort(x) % assume the input array x is a row vector
d = x; % copy x to d first, d is the variable that holds our answer!
for i=numel(x):-1:1 % notice that this loop is decreasing now
changed = 0;
for j = 1:(i-1) % we can actually stop when j is already i-1!, and remember that i is decreasing!
if d(j) > d(j+1)
tmp = d(j);
d(j) = d(j+1);
d(j+1) = tmp;
changed = 1; % something is still swapped
end
end
if changed == 0 % do Google search on the term bubble sort to learn about this enhancement!
break; % stop the bubble sort as soon as you do not see any more swap in an iteration!
end
end
The Art of White Spacing (OK)
function d = my_sort(x) % assume the input array x is a row vector
d = x; % copy x to d first, d is the variable that holds our answer!
for i=numel(x):-1:1 % notice that this loop is decreasing now
changed = 0;
for j = 1:(i-1) % we can actually stop when j is already i-1!, and remember that i is decreasing!
if d(j) > d(j+1)
tmp = d(j);
d(j) = d(j+1);
d(j+1) = tmp;
changed = 1; % something is still swapped
end
end
if changed == 0 % do Google search on the term bubble sort to learn about this enhancement!
break; % stop the bubble sort as soon as you do not see any more swap in an iteration!
end
end
The Art of White Spacing (OK)
function d = my_sort(x) % assume the input array x is a row vector
d = x; % copy x to d first, d is the variable that holds our answer!
for i=numel(x):-1:1 % notice that this loop is decreasing now
changed = 0;
for j = 1:(i-1) % we can actually stop when j is already i-1!, and remember that i is decreasing!
if d(j) > d(j+1)
tmp = d(j);
d(j) = d(j+1);
d(j+1) = tmp;
changed = 1; % something is still swapped
end
end
if changed == 0 % do Google search on the term bubble sort to learn about this enhancement!
break; % stop the bubble sort as soon as you do not see any more swap in an iteration!
end
end
Application 1: Root Finding
• Polynomial equations
–
f(x) = 1*x^2+2*x-1 % the coefficients are p = [1 2 -1]
• Transcendental equations
–
•
Root finding
–
•
f(x) = sin(x) % cannot be expressed as simple algebra
Finding values of x (and y, z, … depending on the number of variables used)
so that the function value is zero.
How to do it in Matlab
–
–
Polynomial equations:
• roots([1 2 -1]) % p is the coefficients of the polynomial, ans = -2.4142 and 0.4142!
• fzero(@(x) x^2+2*x-1, 0) % the result is 0.4142
• fzero(@(x) x^2+2*x-1, -2) % the result is -2.4142
• fsolve(@(x) x^2+2*x-1, 0) % only works if your Matlab has optimization toolbox...
Transcendental equations (cannot use ‘roots’):
• fzero(@(x) x+cos(x), 0) % the result is -0.7391 (see slide 12).
• fsolve(@(x) x+cos(x), 0) % only works if your Matlab has optimization toolbox...
Application 2: Linear Algebra
• Simultaneous equations / Set of Linear Algebraic equations
–
–
•
x=y+1
2x = y
How to do it in Matlab
–
–
–
Rewrite the functions in a standard way.
• 1x - 1y = 1
• 2x - 1y = 0
Convert them to Matrices.
• [1 -1; 2 -1] * [x; y] = [1; 0]
Do Matrix operations in Matlab
• A*z=b
• A-1A * z = A-1 * b
• I * z = A-1 * b
• z = A-1 * b  z = inv(A) * b;
• z = A \ b  more preferred
• z = [1 -1; 2 -1] \ [1; 0]
• z = [-1; -2]  x = -1; y = -2;
Term Assignment - Overview
•
This is 30% of your final IT1005 grade... Be serious with it.
–
–
–
•
Question 1: Trapezium rule for finding integration
–
–
–
•
Simultaneous, Non Linear, Ordinary Differential Equation
Question 3: Similar to Q2, 4 species
–
•
A. Naïve version
B. More accurate version
Note: Colin has revised the ambiguous variable ‘a’ inside function f(t) to be variable ‘c’!
Question 2: Zebra versus Lion
–
•
No plagiarism please, I will do thorough check for every submissions.
Must give strong ‘individual flavor’ in your answers!
Strict deadline, Saturday 5 April 08, 5pm, submit to IVLE “Term Assignment” folder!
Note: Dr Saif has revised xi to xj in the equation there!
Do not worry if you do not know what to do yet.
–
–
–
Listen to these two weeks lectures very carefully!
Dr Saif will touch these topics in the coming lectures, soon.
That is the info for now, stay tuned next week for more information.
Lab 6 + Submission System
•
Q1. Playing with Functions, to reinforce concepts about functions!
–
–
•
Q2. Car Simulation Program
–
–
•
A-B. Short answers! For the commands: either write in M file or MS Word (choose one!)
Q4. FSOLVE
–
–
•
•
A-B. DO NOT be too long winded. Just get to the point.
C. Give me your M file, DO NOT copy the code into MS Word!
Look at ‘additional info/hints’ section! You have tremendous amount of hints there…
• File Name: YourName_q62.m plus other files that you think are necessary!
Q3. FZERO
–
•
A-E. DO NOT give me myfun_51a.m to myfun_52e.m! Just EXPLAIN what you see!
F. Finally, give me the final myfun_51f.m or copy to MS Word (but choose one option only)!
NOTE: FSOLVE is still missing in our Matlab in COM1/114, we will resolve it soon.
Give me whatever necessary, lesser files and lesser codes are better.
ZIP everything and save it as: YourName.zip
Deadline
– Wednesday groups: Tuesday, 25 March 08, 5pm
– Friday groups: Thursday, 27 March 08, 5pm
Free and Easy Time
• Now, you are free to explore Matlab,
especially to find answers for Lab 6
or Term Assignment (at least q1),
or to re-try each slide in Symbolic Math lecture by yourself.
• Want to say Good Friday and Happy Easter to all students, especially for
those who understand the meaning
and celebrate these events .
Download