11.07.2015 Views

Introduction to MATLAB 7 for Engineers - The University of Jordan

Introduction to MATLAB 7 for Engineers - The University of Jordan

Introduction to MATLAB 7 for Engineers - The University of Jordan

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Lecture 6 Computer Applications 0933201 Chapter 4Effective documentation can beaccomplished with the use <strong>of</strong>1. Proper selection <strong>of</strong> variable names <strong>to</strong>reflect the quantities they represent.2. Use <strong>of</strong> comments within the program.3. Use <strong>of</strong> structure charts.4. Use <strong>of</strong> flowcharts.5. A verbal description <strong>of</strong> the program,<strong>of</strong>ten in pseudo-code. (in which naturallanguage and mathematical expressions areused <strong>to</strong> construct statements that look likecomputer statements but without detailedsyntax).Documenting with ChartsTwo types <strong>of</strong> charts aid in developing structuredprograms and in documenting them.<strong>The</strong>se are structure charts and flowcharts.A structure chart is a graphical description showing howthe different parts <strong>of</strong> the program are connected <strong>to</strong>gether.4-6 Z.R.KZ.R.K4-7Structure chart <strong>of</strong> a game program. Figure 4.1–14-8Flowcharts are useful <strong>for</strong>developing and documentingprograms that containconditional statements,because they can display thevarious paths (called“branches”) that a program cantake, depending on how theconditional statements areexecuted.Flowchart representation<strong>of</strong> the if statement.Figure 4.1–2Z.R.K4-9Finding BugsDebugging a program is the process <strong>of</strong> finding andremoving the “bugs,” or errors, in a program.Such errors usually fall in<strong>to</strong> one <strong>of</strong> the followingcategories.1. Syntax errors such as omitting a parenthesis orcomma, or spelling a command name incorrectly.<strong>MATLAB</strong> usually detects the more obvious errorsand displays a message describing the error and itslocation.2. Errors due <strong>to</strong> an incorrect mathematical procedure.<strong>The</strong>se are called runtime errors. <strong>The</strong>y do notnecessarily occur every time the program isexecuted; their occurrence <strong>of</strong>ten depends on theparticular input data. A common example isdivision by zero.Z.R.K4-10To locate a runtime errors, try the following:1. Always test your program with a simpleversion <strong>of</strong> the problem, whose answers canbe checked by hand calculations.2. Display any intermediate calculations byremoving semicolons at the end <strong>of</strong>statements.3. To test user-defined functions, trycommenting out the function line andrunning the file as a script.4. Use the debugging features <strong>of</strong> theEdi<strong>to</strong>r/Debugger, which is discussed inSection 4.7.Z.R.KLogical opera<strong>to</strong>rs Table 4.3–1Opera<strong>to</strong>r Name Definition~ NOT ~A returns an array the same dimension as A; thenew array has ones where A is zero and zeroswhere A is nonzero.& AND A & B returns an array the same dimension as Aand B; the new array has ones where both A and Bhave nonzero elements and zeros where either Aor B is zero.| OR A|Breturns an array the same dimension as Aand B; the new array has ones where at least oneelement in A or B is nonzero and zeros where Aand B are both zero.&& Short-Circuit Opera<strong>to</strong>r <strong>for</strong> scalar logical expressions. A&&BAND returns true if both A and B evaluate <strong>to</strong> true, andfalse if they do not.|| Short-Circuit Opera<strong>to</strong>r <strong>for</strong> scalar logical expressions. A ||BOR returns true if either A or B or both evaluate <strong>to</strong> true,4-11and false if they Z.R.Kdo not.Z.R.K. 2008 Page 2 <strong>of</strong> 7


Lecture 6 Computer Applications 0933201 Chapter 44-12Order <strong>of</strong> precedence <strong>for</strong> opera<strong>to</strong>r types Table 4.3–2PrecedenceOpera<strong>to</strong>r typeFirst Parentheses; evaluated starting withthe innermost pair.Second Arithmetic opera<strong>to</strong>rs and logicalNOT (~); evaluated from left <strong>to</strong> right.Third Relational opera<strong>to</strong>rs; evaluated fromleft <strong>to</strong> right.Fourth Logical AND ( & ).Fifth Logical OR ( | ).Z.R.KLogical functions Table 4.3–4Logical function Definitionall(x) Returns a scalar, which is 1 if all the elements inthe vec<strong>to</strong>r x are nonzero and 0 otherwise.all(A) Returns a row vec<strong>to</strong>r having the same number <strong>of</strong>columns as the matrix A and containing ones andzeros, depending on whether or not the correspondingcolumn <strong>of</strong> A has all nonzero elements.any(x) Returns a scalar, which is 1 if any <strong>of</strong> the elementsin the vec<strong>to</strong>r x is nonzero and 0 otherwise.any(A) Returns a row vec<strong>to</strong>r having the same number <strong>of</strong>columns as A and containing ones and zeros,depending on whether or not the correspondingcolumn <strong>of</strong> the matrix A contains any nonzeroelements.finite(A) Returns an array <strong>of</strong> the same dimension as A withones where the elements <strong>of</strong> A are finite and zeroselsewhere.4-13Z.R.K13 (continued …)Logical function Definitionischar(A) Returns a 1 if A is a character array and 0 therwise.isempty(A) Returns a 1 if A is an empty matrix and 0 otherwise.isinf(A) Returns an array <strong>of</strong> the same dimension as A, withones where A has ‘inf’ and zeros elsewhere.isnan(A) Returns an array <strong>of</strong> the same dimension as A withones where A has ‘NaN’ and zeros elsewhere. (‘NaN’stands <strong>for</strong> “not a number,” which means anundefined result.)isnumeric(A) Returns a 1 if A is a numeric array and 0 otherwise.isreal(A) Returns a 1 if A has no elements with imaginaryparts and 0 otherwise.logical(A) Converts the elements <strong>of</strong> the array A in<strong>to</strong> logicalvalues.xor(A,B) Returns an array the same dimension as A and B;the new array has ones where either A or B isnonzero, but not both, and zeros where A andB are either both nonzero or both zero.4-14Logical functions Table 4.3–4 (continued)Z.R.K4-15Logical Opera<strong>to</strong>rs & and the find Function>>x = [5, -3, 0, 0, 8]; y = [2, 4, 0, 5, 7];>>z = find(x&y)z =1 2 5Note that the find function returns the indices, and notthe values.In the following session, note the difference betweenthe result obtained by y(x&y) and the result obtainedby find(x&y) in the previous example.>>values = y(x&y)values =2 4 7>>how_many = length(values)how_many =3Z.R.K<strong>The</strong> if and else Statement<strong>The</strong> if statement’s basic <strong>for</strong>m isif logical expressionstatementsendEvery if statement must have anaccompanying end statement. <strong>The</strong>end statement marks the end <strong>of</strong> thestatements that are <strong>to</strong> be executedif the logical expression is true.<strong>The</strong> basic structure <strong>for</strong> the use <strong>of</strong>the else statement isif logical expressionstatement group 1elsestatement group 2end4-16Z.R.KFlowchart <strong>of</strong> the elsestructure. Figure 4.4–2More? See pages 201-202.4-17When the test, if logical expression, isper<strong>for</strong>med, where the logical expression maybe an array, the test returns a value <strong>of</strong> true only if allthe elements <strong>of</strong> the logical expression are true!For example, if we fail <strong>to</strong> recognize how the test works,the following statements do not per<strong>for</strong>m the way wemight expect.x = [4,-9,25];if x < 0disp(’Some elements <strong>of</strong> x are negative.’)elsey = sqrt(x)endBecause the test if x < 0 is false, when this programis run it gives the resulty = 2 0 + 3.000i 5Z.R.K. 2008 Page 3 <strong>of</strong> 7Z.R.K


Instead, consider what happens if we test <strong>for</strong> x positive.x = [4,-9,25];if x >= 0y = sqrt(x)elsedisp(’Some elements <strong>of</strong> x are negative.’)endWhen executed, it produces the following message:Some elements <strong>of</strong> x are negative.<strong>The</strong> test if x < 0 is false, and the test if x >= 0also returns a false value because x >= 0 returns thevec<strong>to</strong>r [1,0,1].4-18Lecture 6 Computer Applications 0933201 Chapter 4<strong>The</strong> following statementsif logical expression 1if logical expression 2statementsendendcan be replaced with the more concise programif logical expression 1 & logical expression 2statementsend<strong>The</strong> elseif Statement<strong>The</strong> general <strong>for</strong>m <strong>of</strong> the if statement isif logical expression 1statement group 1elseif logical expression 2statement group 2elsestatement group 3end<strong>The</strong> else and elseif statements may be omitted if not required. However,if both are used, the else statement must come after the elseif statement<strong>to</strong> take care <strong>of</strong> all conditions that might be unaccounted <strong>for</strong>.4-19Z.R.KZ.R.K18For example, suppose thaty = ln(x) <strong>for</strong> x >10,y = sqrt(x) <strong>for</strong> 0 = 0y = sqrt(x)elsey = exp(x) - 1end4-20Flowchart illustrating nestedif statements. Figure 4.4–4Z.R.K20 More? See pages 205-208.4-21Strings ‘ ‘A string is a variable that contains characters.Strings are useful <strong>for</strong> creating input prompts andmessages and <strong>for</strong> s<strong>to</strong>ring and operating on data suchas names and addresses. To create a string variable,enclose the characters in single quotes (’ ’). Forexample, the string variable name is created as follows:>>name = ’Omar Student’name =Omar Student<strong>The</strong> following string, number, is not the same as thevariable number created by typing number = 123.>>number = ’123’number =123Z.R.KStrings and the input Statement<strong>The</strong> prompt program on the next slide uses theisempty(x) function, which returns a 1 if the array xis empty and 0 otherwise.It also uses the input function, whose syntax isx = input(’prompt’, ’string’)orx = input(’prompt’, ’s’)This function displays the string prompt on thescreen, waits <strong>for</strong> input from the keyboard, and returnsthe entered value in the string variable x.<strong>The</strong> function returns an empty matrix if you press theEnter key ( ) without typing anything.4-22Strings and Conditional Statements<strong>The</strong> following prompt program is a script file that allowsthe user <strong>to</strong> answer Yes by typing either Y or y or bypressing the Enter key. Any other response is treated asthe answer No.response = input(’Want <strong>to</strong> ...continue? Y/N [Y]: ’,’s’);if(isempty(response))|(response==’Y’)...|(response==’y’)response = ’Y’elseresponse = ’N’endZ.R.KZ.R.K224-23More? See pages 209-210.Z.R.K. 2008 Page 4 <strong>of</strong> 7


Lecture 6 Computer Applications 0933201 Chapter 4A simple example <strong>of</strong> a while loop isx = 5;k = 0;while x < 25k = k + 1;y(k) = 3*x;x = 2*x-1;end<strong>The</strong> loop variable x is initially assigned the value 5,and it keeps this value until the statement x = 2*x - 1is encountered the first time. Its value then changes <strong>to</strong>9. Be<strong>for</strong>e each pass through the loop, x is checked <strong>to</strong>see if its value is less than 25. If so, the pass is made.If not, the loop is skipped.4-30Another Example <strong>of</strong> a while LoopWrite a script file <strong>to</strong> determine how many terms arerequired <strong>for</strong> the sum <strong>of</strong> the series 5k 2 –2k, k = 1, 2, 3, …<strong>to</strong> exceed 10,000. What is the sum <strong>for</strong> this many terms?<strong>to</strong>tal = 0;k = 0;while <strong>to</strong>tal < 1e+4k = k + 1;<strong>to</strong>tal = 5*k^2 - 2*k + <strong>to</strong>tal;enddisp(’<strong>The</strong> number <strong>of</strong> terms is:’)disp(k)disp(’<strong>The</strong> sum is:’)disp(<strong>to</strong>tal)<strong>The</strong> sum is 10,203 after 18 terms.4-31Z.R.KZ.R.K30 31<strong>The</strong> switch Structure<strong>The</strong> switch structure provides an alternative <strong>to</strong> using theif, elseif, and else commands. Anything programmedusing switch can also be programmed using if structures.However, <strong>for</strong> some applications the switch structure ismore readable than code using the if structure.switch input expression % which can be a scalar or stringcase value1statement group 1case value2statement group 2...otherwisestatement group nend4-32Z.R.K4-33<strong>The</strong> following switch block displays the poin<strong>to</strong>n the compass that corresponds <strong>to</strong> that angle.switch anglecase 45disp(’Northeast’)case 135disp(’Northwest’)case 225disp(’Southwest’)case 315disp(’Southeast’)otherwisedisp(’Direction Unknown’)endZ.R.K33 More? See pages 225-227.<strong>The</strong> Edi<strong>to</strong>r/Debugger containing twoprograms <strong>to</strong> be analyzed. Figure 4.7–1Fourier Seriesx(t) ) = a 0 + n=1 ( a n cos n 0 t + b n sin n n 0 t )Evaluate the following function:x(t) ) = 0.5 + 2/ ( cost – 1/3 cos 3t + 1/5 cos5t– 1/7 cos7t + … ) <strong>for</strong> -10 < t < 10.By using different colors plot the following:1- <strong>The</strong> first two terms.2- On the same figure plot the first three terms.3- On the same figure plot the first four terms.4- On the same figure plot the first five terms.5- By using the general <strong>for</strong>m <strong>of</strong> the function, and by using the<strong>for</strong> or while or … loop. Set n as input variable, On thesame figure plot the first one-hundredterms.4-34 Z.R.KMore? See pages 228-234. 4-35Z.R.KZ.R.K. 2008 Page 6 <strong>of</strong> 7


Lecture 6 Computer Applications 0933201 Chapter 4End <strong>of</strong> Chapter 4Problems Page 241 - 257 !Solve: 2, 5, 11, 16, 23, 24, 25, 33.www.ju.edu.jo\zkhatibZ.R.J.KZ.R.J.K Z.R.KZ.R.K. 2008 Page 7 <strong>of</strong> 7

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!