Lab session on week 10 (6th meeting) Roughly 3 more weeks to end of the semester! Busy weeks for IT1005, but hang on…! IT1005 Lab 6 – Quick Check • Have you all received my reply for lab 6? – My reply should contains: • Remarks on your M files for q1.F and q2.c (look for SH7 tags again) • Remarks on your Microsoft Word file for q1.A-E (or F), q2.A-B-C (plot) • Your marks is stored in the file “Marks.txt” inside the returned zip file! – Survey: Am I too strict this time? – Lower mean and higher variance for Lab 6. L6.Q1.A-F Q1.A. Concept 1: Function usually cannot be run by itself, it must be called from Command Window or from other ‘master’ M-file, especially if you want to specify input arguments! Concept 2: Arguments are ordered from left to right, if you say myfun_51a(2,3), then x = 2 (first argument), y = 3 (second argument). Q1.B. Concept 2: Matlab looks at M-file name when it search for a function definition. Prior to renaming the M-file: not working, After renaming the M-file: working. Btw, DO THIS: function name in Q1.A is now ‘testfun’, but you call it with ‘myfun_51a(2,3)’, it WORKS! It is NOT compulsory to make function name == M-file name many of you make ‘wrong conclusion’. Anyway, to avoid confusion, just make your function name == the associated M-file name! Q1.C. Concept 3: You can call other function(s) from your function as long as they are located in the same folder/directory (or in locations that Matlab knows). Function myfun_51c(a,b) calls myfun_51a(a,b), get the result (which is a+b) then add 5, and return the value to the caller. Q1.D. Concept 4: A variable only exists/known inside its own function workspace. Other functions do not know about this variable. Note: remove ; in sprintf line to see the intermediate result! Q1.E. Concept 5: Because of concept 4 above, if we want other function(s) to know the value of a certain variable, we need to PASS it via that other function’s argument. We only pass VALUE!, the two variable ‘y’s are different variable in different workspace with the same name and same value! Q1.F. Very simple, DO NOT complicate your life, just do this: function returnValue = myfun_51f(x,y) returnValue = 2*x + y; L6.Q2.A-B Q2.A. Best: I want to create a car simulation program based on the data written in Lab 6 instruction . As long as your answer is logical enough (and short), I will give full marks. Q2.B. Up to you, basically three big steps: PS 1: This is what your codes should looks like in the future… modularize your codes like this! PS 2: You can refer to “great circle distance” example that Colin has shown you before! As long as your answer is logical enough (big steps-small steps), I will give full marks. 1. Read Input: ask for inputs You may want to protect from invalid inputs… 2. Compute car velocity and displacement: Do NOT split this or you will just complicate your life! 3. Plot output: look at the lecture note on Graphical Tools to create nicer plots :D No return variable! Use subplots rather than superimposing both plots! Or use two Y axis in Matlab (plotyy)! Remember: DIFFERENT y-axis! You will ‘lie’ with your data if you just superimpose them! Using ylabel to say that the axis are different may not be enough (not obvious!). Q2.C. Here are my codes for the three sub functions in Q2.B above… Remember the lessons from past labs: 1. Reduce trivial comments! 2. Do proper INDENTATION and WHITE SPACING! Only one line, 3. Simpler code will do! For what? 4. retv = v; rets = s; rett= t; are absolutely UNNECESSARY! This function requires 5. Look at my comments in your M files, NO input argument CONVERT DO NOT repeat the same mistakes! Deg to Rad READ INPUTS (read_input.m): F/W/rho, etc PROCESS V MAIN PROGRAM (car_simulator.m) This one is NOT a function! Must split your programs into at least three big steps like this! Master aka main program will control the process! PROCESS (simulate_car.m): Velocity/Displacement/Time PROCESS S PROCESS T PLOT OUTPUTS (plot_output.m): subplot/plotyy This function requires NO return variable! Too complicated if you split this computation! read_input.m function [weight force angle_deg rho time delta_time] = read_input() % Return >1 answers! % uncomment this if you want to see the basic answer % weight = 600; force = 50000; angle_deg = 30; rho = 0.12; time = 10; delta_time = 0.1; return; weight = 0; while weight <= 0; weight = input('Weight of the car (kg): '); end % Btw, do not write while-loop like this force = 0; while force <= 0; force = input('Engine force (N): '); end % I combine 3 lines into 1 to save space! angle_deg = -1; while angle_deg < 0 || angle_deg > 90; angle_deg = input('Gradient of the hill (deg) [0...90]: '); end rho = -1; while rho < 0 || rho > 1; rho = input('Coefficient of friction [0...1]: '); end time = 0; while time <= 0; time = input('Total time (s): '); end delta_time = 0; while delta_time <= 0; delta_time = input('Time increment (s): '); end simulate_car.m (approximate) function [t v s] = simulate_car(weight, force, angle_deg, rho, time, delta_time) % Pass inputs here! angle_rad = angle_deg * pi / 180; % Convert angle to radians. n = time / delta_time; % Specify number of iterations % Create and initialize the array first, Matlab allocate the memory first! t = zeros(1,n+1); s = zeros(1,n+1); v = zeros(1,n+1); g = 9.81; % Compute velocity and displacement. Iterate until end of simulation (n+1 or n are ok). for time=2:(n+1) v(time) = v(time-1) + (force / weight - g * sin(angle_rad) - rho * g * v(time-1)) * delta_time; s(time) = s(time-1) + v(time) * delta_time; % s(t) must be here, we must compute v(t) (above) first t(time) = t(time-1) + delta_time; end % Done, no need to do anything else as t v s are the answers when the above for-loop stops! Bad Plot (1): All blues, S?, V? Population of Zebra? NOOO Population of Lion? NOOO Bad Plot (2): Different Y axis! My PhD thesis involves information visualization. This is called = lying with data… plot_output.m function plot_output(t,v,s) % look ma, NO return variable! subplot(2,1,1); plot(t,v,'b'); legend('velocity (m/s)','Location','SouthEast'); title('The graph of velocity of the car against time'); xlabel('Time (seconds)'); Using subplot ylabel('The velocity (m/s)'); grid; subplot(2,1,2); plot(t,s,'g'); legend('displacement (m)','Location','SouthEast'); title('The graph of displacement of the car against time'); xlabel('Time (seconds)'); ylabel('The displacement (m)'); grid; Using plotyy car_simulator.m (The ‘Boss’) % This is the master M-file that will control the execution of all the other functions. % All our program should be structured like this, many simple sub-functions, one master program, % all files stored in the same folder/directory. Remember this during your HYP days! % Now, you need to press F5 (run) your program from this master program! [weight force angle_deg rho time delta_time] = read_input(); % get user inputs [t v s] = simulate_car(weight, force, angle_deg, rho, time, delta_time); % pass inputs, get outputs plot_output(t,v,s); % pass results from simulate_car to this output function, no return variable needed simulate_car.m (ODE version) function [t v s] = simulate_car(weight, force, angle_deg, rho, time, delta_time) % Pass inputs here! % Let ODE solver do the work! % Note that t, x must always be the first two arguments, additional arguments starts from 3rd! % We can also specify delta_time inside the time span! [t,retVal] = ode45(@(t,x) noName(t, x, weight, force, angle_deg, rho), [0:delta_time:time], [0; 0]); s = retVal(:,1); % first column v = retVal(:,2); % second column % Sub function containing the derivative function retVal = noName(t, x, weight, force, angle_deg, rho) angle_rad = angle_deg * pi / 180; % Convert angle to radians. retVal(1) = x(2); % Derivative of s = v t is just v = x(2); retVal(2) = force / weight - 9.8 * sin(angle_rad) - rho * 9.8 * x(2); % This is the derivative for v retVal = retVal'; % transpose to make this a column vector L6.Q3 and Q4 Q3 and Q4 are dropped for Lab 6. Q3 reappears in Lab 8!, so my answers are removed. Q4 reappears in Lab 7!, so no answer too. Application 3: Symbolic Math • Matlab can answer most (all?) A-level Math questions with ease. • What is the best way to use this feature? – If you are still A-level students • You can use Matlab to do your Math homeworks. – If you are doing tuition to A-level students • You can bring your laptop + Matlab and amaze your students with Matlab’s power. – But you are now University students • Use this feature for your advantage in other? modules… not just for this IT1005! • “Sponsor” message: Buy a copy of Matlab if you do not have it yet! – Or if your copy is not legal >.< • The best way to learn this Symbolic Math is by self-exploration! – Re-type all the examples in each slide of your Symbolic Math lecture note! – Try all A-level Math knowledge that you can remember… Application 3: Symbolic Math • Let’s try. Please start Matlab on your computer! – Fraction as symbol: • sym(3)/sym(5)+sym(1)/sym(2) 11/10 – Differentiation: • • syms f x; f = sin(5*x) ; diff(f) f = 5 * cos(5 * x) f = x^n; diff(f); simplify(ans); pretty(ans) x(n-1) n – Integration: • • f = 5 * cos(5 * x); int(f) we should see f = sin(5 * x) as above. f = x^(n-1) * n; int(f) we should see f = x^n as above. – Limits: • limit(x/abs(x),x,0,’left’); limit(x/abs(x),x,0,’right’) – Factoring/Expanding/Solving polynomials: • • • – f = sym((x-1) * (x-2)); expand(f) f = sym(x^2 - 3*x + 2); factor(f) f = sym(x^2 - 3*x + 2); pretty(solve(f)) 2 and 1 used in Lab 7! TRY OTHER EXAMPLES! • Open your A-level Math text book and try the concepts in Matlab! Application 4: Graphical Tools • What can we do with our plots? – – – – – – Customize the plots with different colors/line styles/markers Add texts/labels to our plot Draw multiple plots on the same figure Draw subplots in one figure Editing individual plot properties Do basic fitting (good thing, typically used to explain your experiments) • Now, test your plotting knowledge • Try to re-create these plots in the next few slides! – Download the data generator M-file at: – http://www.comp.nus.edu.sg/~stevenha/myteaching/investment.m Complete M-file for this plot! (1) Complete M-file for this plot! (2) Complete M-file for this plot! (3) Application 5: ODE (IVP) • ODE: Ordinary Differential Equation – Today, we will focus on IVP: Initial Value Problem • You need to understand this to tackle term assignment q2 and q3. – At least q2! • Spidey fall: – Traditional/Euler method: approximate the derivative (see Lec 2). – IVP ODE version: the answers are the same. See – I have applied this to Lab 6 car simulation program too . • Short summary: – Create a function for the differential equation itself. • function dhdt = triangle(t,h) dhdt = 1; % original linear function h = t, dhdt = 1! (constant) – Specify time span, initial value, use (one of) Matlab IVP solver, and show result: • [t,h] = ode45(@triangle, [0 7], 10); % [0 7] is from time 0 to time 7, 10 is the initial h0! • plot(t,h); Lab 7 Overview • • No ODE yet, perhaps for Lab 8 and definitely for Term Assignment. Q1. CSTR? Erm… >.< – – – • • Q2. A general version of Q1, simple modifications will do (see L6.Q2 style) Q3. Create system of 2 non-linear functions (symbolically), solve the system – • Hint: type “help solve” in Matlab! need to do something to understand the cryptic output! Q4. fsolve, do this in SoC1/815, FoE labs, or if your Matlab has it! – • Truthfully, I do not understand the Chemical Engineering concepts behind this question. >.< But anyway, this is just about solving set of Linear Algebraic equations using Matlab. Can be solved even if you do not understand the equations. >.< You need to understand how to use fsolve for SET of non-linear equations. Deadlines: A busy week for IT1005: Lab 6, Lab 7, and Term Assignment! – – – – – Lab 6 deadline for Wednesday groups: Lab 6 deadline for Friday groups: Lab 7 deadline for Wednesday groups: Lab 7 deadline for Friday groups: Term Assignment for both groups: Tuesday, 25 March 08, 5pm (PASSED) Thursday, 27 March 08, 5pm (PASSED) Friday, 28 March 08, 5pm (YOUR PRIORITY) Sunday, 30 March 08, 5pm (YOUR PRIORITY) Saturday, 5 April 08, 5pm Term Assignment - Overview • This is 30% of your final IT1005 grade... Be serious with it. – – – • Question 1: Trapezium rule for finding integration – – • IVP Question 3: Similar to Q2, 4 species – • • By now, you should already able to answer this question. Buck up if you still do not know how to do this! Question 2: Zebra Population versus Lion Population – • 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! Another IVP, but with 4 equations now. Since the deadline is tight, concentrate doing Lab 7 first! Do Term Assignment afterwards (no Lab 8 next week) – I will dedicate next week session for this! Free and Easy Time • Now, you are free to explore Matlab to: – Find answers for Lab 7 (priority) – Do Term Assignment (q1, q2 should be do-able now) – Re-try each slide in Symbolic Math/ODE lectures by yourself • Note that your Lab TA: – Is not a Chemical Engineering graduate! • He does not understand those complex formulas… – Has forgotten most of his A-level Math >.< • f = ex*sin(x)*cos(x), what is diff(f)?? – Still new with Matlab • Especially the advanced ODE stuffs… • So, please accept my apology if I cannot answer some stuffs this week.