Introduction to MATLAB FOR ENGINEERS by J A Rossiter (Department of Automatic Control and Systems Engineering) This handout summarises basic information on MATLAB and some of the department expectations. More detailed notes are contained in the supporting slides (with voiceover). Learning is supported by occasional lectures and weekly laboratory sessions with demonstrator support and regular small assessments. The content covers 8 credits or about 80 hours of student time. The author’s department has a large focus on managing student transition and independent learning and hence the delivery mechanism reflects: the desire to ensure students are working regularly. but also engaging in more challenging issues such as why is this module important (hence the other assignments). Note: MOLE is our Virtual Learning Environment and this module delivery assumes students access this regularly for assignments. © University of Sheffield 2009 This work is licensed under a Creative Commons Attribution 2.0 License. ACS108 – MATLAB laboratories and assignments Aims, objectives and assessment To introduce the students to the MATLAB software package and the use thereof for solving engineering problems 1. Understand how to define and manipulate variables in MATLAB. 2. Understand how to write m-files (function and script). 3. Use MATLAB to solve engineering problems. 4. Use MATLAB as a tool in report writing. 5. To understand the potential of MATLAB for problem solving. 6. To develop confidence in learning and applying new aspects of MATLAB without help. How to learn MATLAB You must learn to be inquisitive, enquiring, imaginative and most of all INDEPENDENT. This is a topic you learn by doing, not by being taught. Pretend it is a computer game. Write a line of code and see what it does? Try to understand why a particular command has produced a given result. Once you think you know what the command is doing, change the command to test your assumption. Example: 1. TRY >>x=[1 2 3] %%% defines a row vector with coefficients 1,2 and 3 >>n=norm(x) returns a value of 3.7417 2. What do you think this has done. If you are unsure, change the numbers and try again. >> x=[3 4] >>m=norm(x) returns a value of 5 3. Does this look familiar (pythagorous)? 4. Ask for more guidance using ‘help’ >>help norm 5. When you think you have it, try lots of different numbers to verify to yourself that you have got it right. That is, enter problems to which you know the answer and make sure the code gives you back the answer you expect. GETTING AND USING HELP Professional engineers must be independent and use the web, books, manuals, etc to work out how to do something. In this module, we expect you to develop skills at doing this. DO NOT EXPECT DEMONSTRATORS TO TELL YOU ‘How to do it’? A main learning outcome is for you to learn how to work it out by yourself. Consequently, demonstrators will try to lead you into asking the right questions so that you develop more independence and hopefully, a lot more confidence for future studies. MATLAB has a huge built-in help facility as wells as numerous demos to help you learn key topics. Consequently this course does not give detailed lecture notes. If you want detailed guidance on some function or operation, use the built-in help. Practise accessing this frequently to increase your confidence in doing so. 2 Notes and reading Comprehensive notes for MATLAB are included in the software. These notes are intended only to get you started. Many books exist which may also be helpful, e.g. A A B B B B The Math Works Inc., Student Edition of MATLAB for MS-DOS Personal Computer, (Prentice Hall, Englewood Cliffs.) Matlab for engineers explained, F Gustafsson and N Bergman, Springer, ISBN 1852336978 A. Biran and M. Briener, Matlab 5 for engineers, Addison Wesley, 1999, ISBN 0-201-36043-8 R. Pratap, Getting started with Matlab, Oxford University Press, 2002, ISBN 0-19-515014-7 B.D. Hahn, Essential matlab for scientists and engineers, Butterworth and Heineman, 2002, ISBN 0-7506-5240-3 B Daku, Learn matlab fast, Wiley, 2004 (or 2005) 0471274960 Accessing MATLAB Find by loading applications and then following the links as follows: applications/academic/maths and stats/MATLAB** If you wish to install a copy of MATLAB on your own computer you must obtain your own copy. A Student Version of MATLAB is available for purchase from Blackwells. If you want to have the same set of toolboxes as used in ACSE labs you must obtain those listed under the column titled 'Classkit Licences' on the web page: http://www.shef.ac.uk/acse/computing/sw/licencenum.html For more details about the Student Version of MATLAB and how to obtain it: http://www.mathworks.co.uk/academia/student_version/ ACSE web pages with general information about MATLAB are at: http://www.shef.ac.uk/acse/computing/sw/matlab.html ACCESSING FILES DISCUSSED IN THE NOTES All the mfiles discussed in the notes are available for you to run. In order to make sure they are visible you must type the following in the workspace window: addpath \\Boothwood\SHARED6\ACSE\jar\acs108_matlab Alternatively, download all the files to your U drive from MOLE assignments area. MATLAB will run any files in the current directory and the path. If it says a file does not exist, the most likely reason is that you are in the wrong folder or forgot to set the path. INDEPENDENT LEARNING and TRUSTING YOUR OWN JUDGEMENT It is essential that you take ownership of your work and make judgments on what is good and what is not. Would you buy it? If not, why not? Code can be written in many different ways, data can be displayed in different ways. You must decide and justify the way you think works well – your peers will decide if they agree with you. HOWEVER: 1. Submitted code must never crash or it scores ZERO. Would you go back to a shop that sells faulty goods? 2. It must be entirely your own work. CHEATING (i.e., copying etc.) devalues the degree of your colleagues and hence is highly offensive. LECTURES: Audio workbooks are on Boothwood and MOLE. Select the player.html to play them. You will need headphones. 3 Use of comments in programming (2 sides) Comments are essential in good computer code. Without them the code is almost useless in that the USER (your colleagues) will not be able to determine how the code works and hence to edit it when a slightly different purpose is required. It is also important in industry for tracking edits where problems occur following a code change. When you submit some code as part of an assessment, a significant proportion of the marks will be for adequate comments. Comments can be described in three distinctive forms: 1. A file header – this comes at the very top of the code 2. Occasional large blocks of textual comment within the code 3. Short phrases of comment throughout A file header This should give a detailed description of what the code does with specific emphasis on defining the format of the required input arguments and the format of the possible output. The detail should be sufficient for a qualified reader to use the code correctly by simply using the call statement. In many cases it is also good practise to give details of authorship and dates. Where others later edit the code, the edits should also be described with authorship and dates. Occasional large blocks of textual comment within the code Code needs to be well structured. This structure should be evident both visually through appropriate blocking and tabbing and also though wise use of comments. For example, if a block of code performs a specific task, such as matrix inversion, then there should be a left justified paragraph of comments before this block of code describing what the block does, with suitable reference to variables and context. With well commented code, the USER can scan through the main comment blocks to get, quickly, a good overview of how the code is structured and hence operates. Tabbing and line spaces should be used to help the reader identify visually blocks, loops, conditionals, etc. Short phrases of comment throughout Generally, the blocks of comment every 10-20 lines are enough. However, there will be individual lines of code where the operation is not obvious or there is some subtlety. In this case it may be appropriate to add a right justified (on same line as the code in question) brief comment or even a one line left justified comment immediately before the code in question. For illustration an example file is given over the page. 4 TYPICAL FILE HEADER – anything after a % is a comment %%%% File to do Newton-Raphson iteration to solve f(x)=0 %%%% Limited to functions and derivatives that are entered as strings %%%% WARNING: Will fail badly where f'(x)<< f(x), i.e. where assumption of %%%% 1st order Taylor series breaks down %%%% %%%% Function f(x) is entered in a string 'fun' (e.g. fun='x^2+sin(x)') %%%% Function derivative f'(x) is entered as string 'fun_derivative' (e.g. '2*x+cos(x)') %%%% %%%% maxiter is the maximum number of iterations %%%% x0 is a seed for the algorithm %%%% count is the number of iterations used %%%% accuracy is the desired accuracy %%%% x is the solution after count interations %%%% %%%% [x,count] = acs107_file523(fun,fun_derivative,maxiter,x0,accuracy) %%%% %%%% File written by J.A. Rossiter on Nov. 9th 2001 for ACS107 TYPICAL BLOCK COMMENTS (also note tabbing in code to add visualisation) %%% The following code performs the Newton Raphson’s iteration on a function %%% given as fun=f(x) %%% The algorithm is summarised as %%% x[k+1] = x[k] - f(x[k])/f'(x[k]) %%% The iteration continues until either x[k+1]-x[k]<accuracy or the %%% maximum number of iterations is reached. %%% The iteration is seeded with x=y(1) and iterates are stored in y(k). while cont count =count +1; x=y(count-1); y(count) = y(count-1)-eval(fun,x)/eval(fun_derivative,x); if abs(y(count)-y(count-1))<accuracy; cont=0;end if count==maxiter;cont=0;end end TYPICAL MINOR OR INLINE COMMENT g1=tf(1,[1 2 1]); %%% Defines g1 as 1/[s^2 + 2s +1] 5 Generic instructions for assignments and coding in MATLAB (2 sides) File names used for courseworks All filenames should have tags that clearly identify: (i) the author; (ii) the coursework; (iii) the task. YOU MUST use the convention: userid_cwj_taski.m Example. My email userid is co1jar and I am writing a file to do task2 for coursework 2. I use the name: co1jar_cw2_task2.m Warning: I might put all your files in a single folder, so if you do not use unique and personalised names, your files could get overwritten. Also, I won’t know who it came from. Files not using this convention will be awarded ZERO. Checking your own work and professionalism 1. A fundamental skill for a professional engineer is to be able to test their own work. How do you know your code is working correctly? Would you bet your house on it? What tests can you create to test your code? How many different tests and scenarios are enough? What evidence can you give that you have tested your code and therefore trust it? You must ensure your code never crashes except when misused. NOTE: One essential test is to type the filename in the command window (with appropriate inputs/outputs if required). ** See section on debugging code. 2. A further key skill is the ability to learn independently. To use the resources provided to learn what is needed for the task. In this module, you will need to ‘develop independence’. Identify what tools you need and independently learn how to use these tools and apply them correctly. What resources do you have provided? Do you know how to search through them and use them? Typical questions YOU may need to answer before starting a task 1. How will the user supply data? 2. How will you supply the answers? 3. Will you have strict naming conventions for variables and files? 4. How do you ensure your programmes and variable names do not interfere with each other? 5. How will you provide guidance notes to any user? 6. How do you know your code is correct? 7. What tests have you used? General points 1. Read the comments on last years’ submissions (on webct). Make sure your files do not make the same mistakes. Ensure you have semi-colons at the end of most lines. 2. Make sure you always clean a figure window before using it unless you really do want to inherit the current contents. Always use a hold off after a hold on. 3. Have you given comprehensive comments and headers within all your code? 6 Debugging code The biggest failings of past students are listed next. When preparing your code use a tick list to ensure you do not make these mistakes. ADVICE 1: The easiest way to find errors in code is to type the filename in the command window. This way MATLAB will tell you which line number has failed and the nature of the error. The more you practise this, the easier you will find it to understand the comments MATLAB gives you. Use breaks (or keyboards) to interrogate more closely. ADVICE 2: Function files are more robust than script files because the user is forced to enter the correct input data and thus the file is immunised against a corrupted workspace. TYPICAL PROBLEMS File fails to run when demonstrator types filename on their own machine. The command window is flooded with numeric data so that the user is confused. File crashes when an option the user did not complete is selected. Figures unreadable Variable name confusion File not found ‘Exceeds dimensions’ Unexpected ‘****’ Variable undefined POSSIBLE REASONS Student did not test with different workspaces (i.e. empty workspace, full workspace, …) Programme relies on a given folder structure or other files or previous use of an addpath statement. File assumes known data and not robust to variations in user supplied data. Student always ran file using F5 and never by typing name in command window. Student forgot to put semi-colons at the end of lines where the result does not need to be displayed. If you do not do all the tasks, make sure your code does not crash by allowing the path but returning a simple display such as ‘task not done’. Inappropriate use of subplots. Forgot to clean figure before use. Left a hold on Did not give suitable labels and legend. Poor choice of scales. Overwrote a desired figure. Was not careful with variable names and thus file tries to use wrong data or data if incorrect size and format. Variable name matches a filename so MATLAB cannot access file as variables have priority. (May come up as ‘incorrect dimension’ or similar error) Student code relied on a path set up on their computer which is not available on demonstrator’s computer. Student in wrong folder. Student forgot to use appropriate addpath statement. You have asked for an index that is not defined. For instance if A is a 3 by 3 matrix, but you use A(4,2) which looks for the 4th row which does not exist. Always match if, switch, while, for with an end statement and add an inline comment to make sure you know which end goes with which statement. Tried to use a function file without supplying sufficient inputs in the call statement. Tried to use a variable before it has been defined. Code is always sequential. 7 Assignment organisation and assessment Laboratory 1 Laboratory 2 Semester 1 Weeks 1-3 Weeks 4-7 Laboratory 3 Weeks 7-11 Laboratory 4 Semester 2 Weeks 1-3 Laboratory 5 Weeks 4-6 Laboratory 6 Weeks 7-9 Summary content Familiarisation Headers, comments, conditionals and function files Engineering problem solving Formative Assessment In class test in week 3 Submit code and report. Checked within lab by peers and demonstrators. Quiz delivered via MOLE Value 2,1,-1 Matrices and image processing Use in mathematics, measurement and stastistics. Use in control engineering + GUIs Demonstrate in class in week 3 Report and demonstrate code in laboratory. 3,2,-2 Produce a brief report and demonstrate a GUI. 3,2,-2 3,2,-2 5,3,-2 Part of ACS103 You are encouraged to seek feedback on your work at all times so that you understand what constitutes good and unsatisfactory work. [NOTE: negative marks if unsatisfactory!] Summative assessment [18% of ACS108 module mark] The MATLAB component of ACS108 will include a single 2 hour exam during the examination weeks of semester 2. During this test students will need to create some code, solve some engineering problems. The content of the test will be based on all the formative assessments of laboratories 1-6, so students should ensure that they have maintained all the relevant code in a folder on their U: drive so that it is accessible during the test. IMPORTANCE of assessment 1. Engineers use computers and software to solve problems not readily amenable to pen and paper, for instance repetitive tasks or numerical intensive tasks. 2. Software is often used to produce results that are then reformatted into a report. 3. Your report will be presented to other people. Is it convincing? Will you get the contract? You will need to write code to solve engineering problems and then produce a report which demonstrates the solution and gives evidence for the correctness of your code. All code will be in appendices. You will need to demonstrate your code to your peers and convince them that it is good as if you were presenting to a boss at work. Matlabpath: Matlab will search in a number of folders (directories) to find a file with the name that you have entered at the command window. The default path has: (i) the current directory and (ii) all the installed matlab toolboxes. Type ‘path’ to view the current search path. You can extend the path using the command ‘addpath’. This enables you to establish one or more utility folders and always have those files visible, even when your workspace is in a different folder. Use path to check your success. Use the option from the Matlab toolbar file_setpath to achieve a similar end. 8 Feedback and comments on past student work CODING: Aspects that students usually do badly are: Headers to files are not informative enough about what the file does or how to use it. Similar remarks may apply to comments. If you have problems with how to code some tasks, do ask me or a demonstrator. Clearly students are not clued up on logical variables and how to use these for efficient coding. Ask me! Students do not understand how to use mat files. Work on this and if stuck, ask me! REPORT: Typical student faults were: No title. No author. Not written in the style of a standalone report. No appendices and hence no code for reader to look at. No figures or insufficient figures. Insufficient (or no) labelling of figures. EFFICIENCY: In many cases, students did not solve a problem in the most efficient manner. This will come with practise but a general guideline is: Only use the symbolic toolbox and associated routines if you need an algebraic answer. If numerical answers are required, usually there are easier routines. There is strong evidence that students are not confident and fast users of the techniques we have practised so far. MATLAB will only help you with your studies if you become a proficient user of the basics. This simply involves time and practise. Engineering: Most students did not use figures well in task 1 to illustrate the key differences. Don’t just look at the question, think about what message you are communicating and ask which figures/examples will do this best. The main purpose of the report is to communicate an engineering message! Also think about how the USER will use your files. Make data entry as intuitive and simple as possible so they can try different functions, domains, etc. Figures: There was still an absence of obvious things like titles and labels on some and poor choices of line types that made the figure hard to read. Also, you should import actual data (such as f(x), damping, etc.) into the title and labels so that the figure refers to the actual data on which it is based. To say ‘function’ is not helpful. The printing of figures was very poor in many reports with lines being unreadable and/or indistinguishable. Variable inputs: it was not clear how many of you would allow f(x) to be altered by the program user without having to change the code itself.. Headers: Many headers did not say how to use a file. See me in a lab for more guidance on this. Also the header should give an overview of what a file does, including subfunctions where relevant, as in a GUI. 9 ACS108 MATLAB practice assessment for semester 1 of 2009-10 Students are reminded that the main assessment for MATLAB is at the end of semester 2. Any interim assignments are intended to be formative more than summative and students will get full marks for reasonable, but not perfect, work. However, on the contrary side, work that is clearly unsatisfactory will gain a penalty for lack of professionalism which is a key learning outcome of this module and students should not b able to pass easily while displaying poor professional behaviours. Example assessment 1: Scheduled for Friday of week 3 The actual assessment will be provided on the day. Illustrate the solution to the following inequality in the domain [-0.5,2.5] (2 x 1) sinh x 4 ( x 1)( x 2) Your figure should be well labelled and make sensible use of colours/line types. When you think you have finished, ask the demonstrator to check off your work. The demonstrator should be able to run your code by typing the filename in the workspace, beginning from an empty workspace. They will expect to see a suitable figure as well as checking your code. Your actual test will be similar. Marks (as part of ACS108) are: 2 for good work 1 for satisfactory work -1 for unsatisfactory work [NO RESITS ALLOWED] 10 Practice assessment 2 1. Question What is the equation of the tangent to the following at x=0.2? x 2 cos( 4 2 x ) cos x sinh x z log(sin( x) 0.1) Answer Q1 Marks 4 Evaluate the tangent at x=0.3. 2. Find the domain where x>-1 and f(x)>=g(x). What is the distance between the minimum and maximum of this domain? 1 f ( x) ( x 1)( x 2)( x 1); g ( x) x Q2 3. What is the solution y(t) of the following ODE evaluated at t=2? d 2 y dy 2 y sin( t ), y (0) y (0) 1 dt 2 dt Q3 Find the solution of the following simultaneous equations and then determine w=x/yz. x 3 y z 2.1 Q4 4. 4 4 4 0.32 x 1.85 y 1.21z 4 2 x 1.46 y 0.012 z 0.31 5. 6. 7. 8. 1 0 4 3 8 2 3 5 1 1 4 What is the determinant of 0 1 2 6 0 4 What is the coefficient of the (x-1)2 term in the Taylor series expansion of z(x) taken about x=1. z cos( 2 x) sin 3 x sinh x Q6 Find the best least squares fit quartic to the curve y=tan(2x) using 30 equispaced points in the domain 0.6 x 0.7 . What is the coefficient of x3 in this quartic? Find the value of x which minimises f(x) in the domain 1.2 x 3.5 . Q7 2x 17 9 Find a root of p(w) with largest modulus. What is the real part? f ( x) ( x 2 1) sin 9. Q5 x 4 4 Q8 4 cos Q9 4 p( w) w w 3w 2w 5 5 4 2 10. Find the definite integral. Q10 4 11 0.5 (e 0.2 x sin x 2 1 x cos )dx 2 6 x 11. Find the closed-loop step response of a loop with system transfer function G(s) and controller P(s). 3 ( s 0.1) G( s) ; P( s ) ( s 1)( s 2) ( s 0.01) What is the output at t=4.5 seconds ? Q11 12 Q12 4 Q13 4 13 14 15 16 Find the peak value of the open-loop step response of M(s) where 3 M (s) 2 ( s 0.3s 1) Find the closed-loop poles with unity negative feedback for an open-loop system T(s). Give the closed-loop pole of largest magnitude. 3( s 5) T (s) 2 ( s 3s 2)( s 2) Find the savings growth for a scheme whereby you are paid annual interest of 4%, compounded monthly, with an annual bonus of £100 if the total invested is over £5,000. The initial investment is £4500 and is invested for 10 years. The final savings are? Upload the data (mydata) from the mat file examdata.mat. What is the average of this data? Write a function file with a call statement of 4 Q14 4 Q15 4 [out1,out2] = examfile(in1,in2,in3) to do the following. out1 is the product of the three inputs unless this product is negative in which case it is the square of the product. Take the value ‘ in1 minus in2’ and divide by in3. This result is the coefficient ‘a’ in the function f=sin(ax). Evaluate f(pi). If f(pi) is greater than out1 than out2 is f(pi), otherwise out2 is f(2*pi). If the user inadvertently enters only two inputs, then the outputs should match the inputs. If the user requests the wrong number of outputs or enters just one input, the file should not crash but the output can be an empty matrix. Now test your file by writing Q16 = testmyexamfile [20] The file examfile.m will be assessed for its header and comments. Copy this code into the text box provided. Store the code you used for all the calculation questions in a single script file (myscript). Make sure it is clear which lines of code are relevant for which questions. Copy this code into the text box provided. 12 20 Questions to help you prepare for the exam What is the gradient of the tangent to the following at x=1. x 2 cos(e 2 x ) sin( 0.4 x) cosh x z log(tan( x) 1) What is the solution y(t) of the following ODE evaluated at t=0.5? d2y dy 5 2 y 2, y (0) 0.1; y (0) 0 2 dt dt Find the solution of the following simultaneous equations and then determine w=x+ y- z. 2 x 3 y z 2.1 0.4 x 0.75 y 10.1z 4.3 2 x 1.1y 0.15 z Find the co-ordinates of the minimum stationary point of the following function. h( z ) 2( z 1)( z 5)( z 2 2) You are given matrices A,B,C,D in the mat file (inclasstest1_matfile.mat on Boothwood). Find the matrix E=C*B*A+D; the answer is the element of E in the 3rd row and 2nd column. What is the coefficient of the x5 in the Taylor series expansion of z(x) taken about x=0. z x cos(e 2 x ) sin 0.2 x sinh x [See taylor.m] Find the best fit cubic to the curve y=0.2*sin(3x) using 50 equispaced points in the domain 0.2 x 0.35 . What is the coefficient of x2 in this cubic? Find the value of x which minimises f(x) in the domain 1.2 x 3.5 . x x x f ( x) ( 0.1) sin cos 4 6 3 Find the solution for x to: x x sin( x ) cos( x )2 7 6 Which of the following systems has a step response with the largest first peak? Find the root(s) of p(w) with largest modulus. p( w) w 4 3w 2 2w 4 Find the definite integral. 1 x cos )dx 8 x 9 0.2 For G(s)=6/[(s(s+2)(s+3)] determine: (i) the peak of the open-loop step response; (ii) the closedloop poles when connected with unity negative feedback; (iii) the closed-loop output at t=0.7seconds for a step response. Find the variance of the vector v=1+rand(1,50) 0.5 ([ x 1] sin x 13 Credits This resource was created by the University of Sheffield and released as an open educational resource through the Open Engineering Resources project of the HE Academy Engineering Subject Centre. The Open Engineering Resources project was funded by HEFCE and part of the JISC/HE Academy UKOER programme. © University of Sheffield 2009 This work is licensed under a Creative Commons Attribution 2.0 License. The name of the University of Sheffield and the logo are the name and registered marks of the University of Sheffield. To the fullest extent permitted by law the University of Sheffield reserves all its rights in its name and marks which may not be used except with its written permission. The JISC logo is licensed under the terms of the Creative Commons Attribution-Non-Commercial-No Derivative Works 2.0 UK: England & Wales Licence. All reproductions must comply with the terms of that licence. The HEA logo is owned by the Higher Education Academy Limited may be freely distributed and copied for educational purposes only, provided that appropriate acknowledgement is given to the Higher Education Academy as the copyright holder and original publisher. Where Matlab® screenshots are included, they appear courtesy of The MathWorks, 14