1 / 19

MatLAB Lesson 8 : M-file Programming II

MatLAB Lesson 8 : M-file Programming II. Edward Cheung email: icec@polyu.edu.hk Room W311g. 2008. Switch & Case. Structure for pick one condition out of several cases Anything that you can do with switch & case could be done with if/else/elseif but the programme is more readable

horace
Download Presentation

MatLAB Lesson 8 : M-file Programming II

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MatLABLesson 8 : M-file Programming II Edward Cheung email: icec@polyu.edu.hk Room W311g 2008

  2. Switch & Case • Structure for pick one condition out of several cases • Anything that you can do with switch & case could be done with if/else/elseif but the programme is more readable • The criterion can be either a scalar or a string • Once the truth case has been hit, the rest of the cases will be ignored • Structure switch expression/variable case option1 statements case option2 statements otherwise statements end

  3. Example on Switch & Case %Determine the sign of an input number n=input('Please input a number'); x=sign(n); switch x case -1 disp('The input number is negative') case 0 disp('The input number is zero') case 1 disp('The input number is positive') end

  4. Example on flow control with strings % Example: filename ex_switch.m % An algorithm to check if a user has enter a correct % module code code='IC3003'; course=input('Training Module Number for MatLab=','s'); switch course case code disp('Correct') otherwise disp('Wrong!') if code(1:2)==course(1:2) %first 2 char equal? disp('but the department code is correct.') end end

  5. Loops • For loop • Use when the number of passes are known ahead of time • While loop • Use when the loop must terminate when a specific condition is met. • Automatic indentation is available on the editor/debugger when pressing the enter key until an end statement is reached.

  6. Example – define a new matrix using for loop >> for k=1:5 a(k)=k^2 end a = 1 a = 1 4 a = 1 4 9 a = 1 4 9 16 a = 1 4 9 16 25

  7. Another example using for loop • The for loop will execute once for every element of the index matrix k >> for K=[1 3 5] A(K)=K end A = 1 A = 1 0 3 A = 1 0 3 0 5 • For zero is inserted in a(2) and a(4) when a(3) and a(5) are appended to a

  8. While Loop • Problems that can be solved with a while loop can also be solved with a for loop • Use while loop if you don’t care the number of looping • Remember to update the control variable on every pass through the loop to avoid infinite looping

  9. Example % create a table of degrees to radians % in 10 degree intervals with while loop clear,clc k=1; while k<=36 degree(k)=k*10; radians(k)=degree(k)*pi/180; k=k+1; end % create a table table=[degree;radians] disp(' Conversion Table') disp(' Degree Radian') fprintf('%8.0f %8.2f \n',table)

  10. Efficiency of Loops • In MatLab array operations are more effective than Loops (for & while) • Minimize the amount of I/O when using a loop. Printing output to screen will increase execution time • Example • Create a large matrix, perform a scalar multiplication calculation and measure time elapsed using for loop and array operation • We measure the elapsed time take for execution instead of the actual time for programme execution because we are running the application on a multi-task environment

  11. Example – programme elapsed time - array % Create a 200 row square matrix A % Scalar multiplication with pi % Measure elapsed time using tic/toc % filename: ex_ttime_array.m clear A=ones(200); tic B=A*pi; t=toc; disp('The elapsed time using array operation is') disp(t)

  12. Example – programme elapsed time - loop % Create a 200 row square matrix A % Scalar multiplication with pi % Measure elapsed time using tic/toc % filename: ex_ttime_loop.m clear A=ones(200); tic for k=1:length(A(:)) B(k)=A(k)*pi; end t=toc; disp('The elapsed time using loop is') disp(t)

  13. Example using etime & clock % Create a 200 row square matrix A % Scalar multiplication with pi % Measure elapsed time using etime % filename: ex_etime_loop.m clear A=ones(200); starttime=clock; for k=1:length(A(:)) B(k)=A(k)*pi; end elapsedtime=etime(clock,starttime); disp('elapsed time using loop is') disp(elapsedtime)

  14. Profiling • Reports time spent in each line of m-file • Identify problematic lines >> profile on >> sphere(300) >> profile report >> profile off

  15. Structure of Programme • The first comment line in a M-file is searchable by the lookfor command. It make sense to put keywords in the first line. • Typical structure • Comments Section • Name of programme, keywords in first line • Creation Date, Programmer’s Names • Definitions of all input & output variables in subsections with units of measurement • Definitions of variables used in the calculation in another section • Name of every user-defined function used in the programme

  16. Try Catch Block • When MatLab detects an error while executing code in the try block, it will pass the control to the catch block immediately for error handling. • Example:- Clear try variable_never_exist catch fprintf('ERROR=%s \n Programme terminated gracefully. \n',lasterr) end

  17. Structure of Programme (cont.) • Input Section • Input data and/or the input function for data entry to this programme (comments where appropriate) • Calculation Section • Output Section • Function for display, plotting, I/O device, etc. • Good practice • Make your programme readable • Check existence of variables and functions • Generate test cases

  18. The Difference Function • Y = diff(X) calculates differences between adjacent elements of X. • If X is a vector, then diff(X) returns a vector, one element shorter than X, of differences between adjacent elements: • [X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)] • If X is a matrix, then diff(X) returns a matrix of row differences: • [X(2:m,:)-X(1:m-1,:)] • Y = diff(X,n) applies diff recursively n times, resulting in the nth difference; • diff(X,2) == diff(diff(X))

  19. Examples on diff >> x=[1 3 4 7 4] diff(x) ans = 2 1 3 -3 >> diff(x,2) ans = -1 2 -6 >> diff(x,3) ans = 3 -8 >> diff(x,4) ans = -11 >> x=[1 3 5;7 9 10;11 13 15]; x = 1 3 5 7 9 10 11 13 15 >> diff(x) ans = 6 6 5 4 4 5

More Related