Presentation is loading. Please wait.

Presentation is loading. Please wait.

Matlab Review Exam 2 – Oct 28, 2009. Exam Reminders Open book. Only Matlab book, no notes or loose papers in book. Open book. Only Matlab book, no notes.

Similar presentations


Presentation on theme: "Matlab Review Exam 2 – Oct 28, 2009. Exam Reminders Open book. Only Matlab book, no notes or loose papers in book. Open book. Only Matlab book, no notes."— Presentation transcript:

1 Matlab Review Exam 2 – Oct 28, 2009

2 Exam Reminders Open book. Only Matlab book, no notes or loose papers in book. Open book. Only Matlab book, no notes or loose papers in book. Bring pen, calculator, and ruler. Bring pen, calculator, and ruler. Arrive on time Arrive on time Leave backpacks, cellphones etc along the walls Leave backpacks, cellphones etc along the walls Skip a chair between you and the next person Skip a chair between you and the next person Paper and stapler will be provided Paper and stapler will be provided

3 Important Topics Figuring out answer for given Matlab commands or scripts Figuring out answer for given Matlab commands or scripts Polynomials: evaluating them, plotting them, determining min or max or roots Polynomials: evaluating them, plotting them, determining min or max or roots Writing a Matlab script to solve a given engineering problem Writing a Matlab script to solve a given engineering problem Writing scripts for functions Writing scripts for functions

4 Good Slides to Review Extracted from all chapter slides

5 Scalar Arithmetic Operations Table 1.1–1 1-5 Symbol Operation MATLAB form ^ exponentiation: a b a^b * multiplication: ab a*b / right division: a/b a/b \ left division: b/a a\b + addition: a + b a + b - subtraction: a - b a - b

6 Order of Precedence Table 1.1–2 1-6 Precedence Operation FirstParentheses, evaluated starting with the innermost pair. SecondExponentiation, evaluated from left to right. ThirdMultiplication and division with equal precedence, evaluated from left to right. FourthAddition and subtraction with equal precedence, evaluated from left to right.

7 Examples of Precedence >> 8 + 3*5 ans = 23 >> 8 + (3*5) ans = 23 >>(8 + 3)*5 ans = 55 >>4^2­12­ 8/4*2 ans = 0 >>4^2­12­ 8/(4*2) ans = 3 1-7 (continued …)

8 Examples of Precedence (continued) >> 3*4^2 + 5 ans = 53 >>(3*4)^2 + 5 ans = 149 >>27^(1/3) + 32^(0.2) ans = 5 >>27^(1/3) + 32^0.2 ans = 5 >>27^1/3 + 32^0.2 ans = 11 1-8

9 Arrays The numbers 0, 0.1, 0.2, …, 10 can be assigned to the variable u by typing u = [0:0.1:10]. To compute w = 5 sin u for u = 0, 0.1, 0.2, …, 10, the session is; >>u = [0:0.1:10]; >>w = 5*sin(u); The single line, w = 5*sin(u), computed the formula w = 5 sin u 101 times. 1-15

10 Array Index >>u(7) ans = 0.6000 >>w(7) ans = 2.8232 Use the length function to determine how many values are in an array. >>m = length(w) m = 101 1-16 More? See pages 19-20.

11 Polynomial Roots To find the roots of x 3 – 7x 2 + 40x – 34 = 0, the session is >>a = [1,-7,40,-34]; >>roots(a) ans = 3.0000 + 5.000i 3.0000 - 5.000i 1.0000 The roots are x = 1 and x = 3 ± 5i. 1-17

12 Solution of Linear Algebraic Equations 6x + 12y + 4z = 70 7x – 2y + 3z = 5 2x + 8y – 9z = 64 >>A = [6,12,4;7,-2,3;2,8,-9]; >>B = [70;5;64]; >>Solution = A\B Solution = 3 5 -2 The solution is x = 3, y = 5, and z = –2. 1-26 More? See page 28.

13 You can perform operations in MATLAB in two ways: 1. In the interactive mode, in which all commands are entered directly in the Command window, or 2.By running a MATLAB program stored in script file. This type of file contains MATLAB commands, so running it is equivalent to typing all the commands—one at a time— at the Command window prompt. You can run the file by typing its name at the Command window prompt. 1-27 More? See pages 29-32.

14 COMMENTS The comment symbol may be put anywhere in the line. MATLAB ignores everything to the right of the % symbol. For example, >>% This is a comment. >>x = 2+3 % So is this. x = 5 Note that the portion of the line before the % sign is executed to compute x. 1-28

15 Input/output commands Table 1.4–2 1-35 CommandDescription disp(A)Displays the contents, but not the name, of the array A. disp(’text’)Displays the text string enclosed within quotes. x = input(’text’)Displays the text in quotes, waits for user input from the keyboard, and stores the value in x. x = input(’text’,’s’)Displays the text in quotes, waits for user input from the keyboard, and stores the input as a string in x.

16 Example of a Script File Problem: The speed v of a falling object dropped with no initial velocity is given as a function of time t by v = gt. Plot v as a function of t for 0 ≤ t ≤ t f, where t f is the final time entered by the user. 1-36 (continued …)

17 Example of a Script File (continued) % Program falling_speed.m: % Plots speed of a falling object. % Created on March 1, 2004 by W. Palm % % Input Variable: % tf = final time (in seconds) % % Output Variables: % t = array of times at which speed is % computed (in seconds) % v = array of speeds (meters/second) % (continued …) 1-37

18 Example of a Script File (continued) % Parameter Value: g = 9.81; % Acceleration in SI units % % Input section: tf = input(’Enter final time in seconds:’); % (continued …) 1-38

19 Example of a Script File (continued) % Calculation section: dt = tf/500; % Create an array of 501 time values. t = [0:dt:tf]; % Compute speed values. v = g*t; % % Output section: Plot(t,v),xlabel(’t (s)’),ylabel(’v m/s)’) 1-39 More? See pages 37-38.

20 Relational operators Table 1.6–1 1-44 RelationalMeaning operator <Less than. <=Less than or equal to. >Greater than. >=Greater than or equal to. ==Equal to. ~=Not equal to.

21 Examples of Relational Operators >> x = [6,3,9]; y = [14,2,9]; >> z = (x < y) z = 1 0 0 >>z = ( x > y) z = 0 1 0 >>z = (x ~= y) z = 1 1 0 >>z = ( x == y) z = 0 0 1 >>z = (x > 8) z = 0 0 1 1-45 More? See pages 44-45.

22 The find Function find(x) computes an array containing the indices of the nonzero elements of the numeric array x. For example >>x = [-2, 0, 4]; >>y = find(x) Y = 1 3 The resulting array y = [1, 3] indicates that the first and third elements of x are nonzero. 1-46

23 Note the difference between the result obtained by x(x<y) and the result obtained by find(x<y). >>x = [6,3,9,11];y = [14,2,9,13]; >>values = x(x<y) values = 6 11 >>how_many = length(values) how_many = 2 >>indices = find(x<y) indices = 1 4 1-47 More? See pages 45-46.

24 The if Statement The general form of the if statement is if expression commands elseif expression commands else commands end The else and elseif statements may be omitted if not required. 1-48

25 1-49 Suppose that we want to compute y such that 15√4x + 10if x ≥ 9 10x + 10if 0 ≤ x < 9 10if x < 0 The following statements will compute y, assuming that the variable x already has a scalar value. if x >= 9 y = 15*sqrt(4x) + 10 elseif x >= 0 y = 10*x + 10 else y = 10 end Note that the elseif statement does not require a separate end statement. y = More? See pages 47-48.

26 To create a row vector, separate the elements by semicolons. For example, >>p = [3,7,9] p = 3 7 9 You can create a column vector by using the transpose notation ('). >>p = [3,7,9]' p = 3 7 9 2-3

27 You can also create a column vector by separating the elements by semicolons. For example, >>g = [3;7;9] g = 3 7 9 2-4

28 2-5 You can create vectors by ''appending'' one vector to another. For example, to create the row vector u whose first three columns contain the values of r = [2,4,20] and whose fourth, fifth, and sixth columns contain the values of w = [9,-6,3], you type u = [r,w]. The result is the vector u = [2,4,20,9,-6,3].

29 The colon operator (:) easily generates a large vector of regularly spaced elements. Typing >>x = [m:q:n] creates a vector x of values with a spacing q. The first value is m. The last value is n if m - n is an integer multiple of q. If not, the last value is less than n. 2-6

30 For example, typing x = [0:2:8] creates the vector x = [0,2,4,6,8], whereas typing x = [0:2:7] creates the vector x = [0,2,4,6]. To create a row vector z consisting of the values from 5 to 8 in steps of 0.1, type z = [5:0.1:8]. If the increment q is omitted, it is presumed to be 1. Thus typing y = [-3:2] produces the vector y = [-3,-2,-1,0,1,2]. 2-7

31 Matrices A matrix has multiple rows and columns. For example, the matrix has four rows and three columns. Vectors are special cases of matrices having one row or one column. M = 2 4 10 16 3 7 8 4 9 3 12 15 2-12 More? See page 73.

32 Creating Matrices If the matrix is small you can type it row by row, separating the elements in a given row with spaces or commas and separating the rows with semicolons. For example, typing >>A = [2,4,10;16,3,7]; creates the following matrix: 2 4 10 16 3 7 Remember, spaces or commas separate elements in different columns, whereas semicolons separate elements in different rows. A = 2-13

33 Creating Matrices from Vectors Suppose a = [1,3,5] and b = [7,9,11] (row vectors). Note the difference between the results given by [a b] and [a;b] in the following session: >>c = [a b]; c = 1 3 5 7 9 11 >>D = [a;b] D = 1 3 5 7 9 11 2-14

34 You need not use symbols to create a new array. For example, you can type >> D = [[1,3,5];[7,9,11]]; 2-15 More? See pages 73 – 74.

35 Array Addressing The colon operator selects individual elements, rows, columns, or ''subarrays'' of arrays. Here are some examples: v(:) represents all the row or column elements of the vector v. v(2:5) represents the second through fifth elements; that is v(2), v(3), v(4), v(5). A(:,3) denotes all the elements in the third column of the matrix A. A(:,2:5) denotes all the elements in the second through fifth columns of A. A(2:3,1:3) denotes all the elements in the second and third rows that are also in the first through third columns. 2-16

36 You can use array indices to extract a smaller array from another array. For example, if you first create the array B B = 2-17 C =C = 16 3 7 8 4 9 2 4 10 13 16 3 7 18 8 4 9 25 3 12 15 17 then type C = B(2:3,1:3), you can produce the following array: More? See pages 75-76.

37 Array Addition and Subtraction 6 –2 10 3 + 9 8 –12 14 = 15 6 –2 17 Array subtraction is performed in a similar way. The addition shown in equation 2.3–1 is performed in MATLAB as follows: >>A = [6,-2;10,3]; >>B = [9,8;-12,14] >>A+B ans = 15 6 -2 17 For example: 2-27 (2.3-1) More? See page 85.

38 Multiplying a matrix A by a scalar w produces a matrix whose elements are the elements of A multiplied by w. For example: 3 2 9 5 –7 = 6 27 15 –21 This multiplication is performed in MATLAB as follows: >>A = [2, 9; 5,-7]; >>3*A ans = 6 27 15 -21 2-29

39 Multiplication of an array by a scalar is easily defined and easily carried out. However, multiplication of two arrays is not so straightforward. MATLAB uses two definitions of multiplication: (1)array multiplication (also called element-by-element multiplication), and (2)matrix multiplication. 2-30

40 Division and exponentiation must also be carefully defined when you are dealing with operations between two arrays. MATLAB has two forms of arithmetic operations on arrays. Next we introduce one form, called array operations, which are also called element-by-element operations. Then we will introduce matrix operations. Each form has its own applications. Division and exponentiation must also be carefully defined when you are dealing with operations between two arrays. 2-31

41 Element-by-element operations: Table 2.3–1 Symbol + - + -.*./.\.^ Examples [6,3]+2=[8,5] [8,3]-5=[3,-2] [6,5]+[4,8]=[10,13] [6,5]-[4,8]=[2,-3] [3,5].*[4,8]=[12,40] [2,5]./[4,8]=[2/4,5/8] [2,5].\[4,8]=[2\4,5\8] [3,5].^2=[3^2,5^2] 2.^[3,5]=[2^3,2^5] [3,5].^[2,4]=[3^2,5^4] Operation Scalar-array addition Scalar-array subtraction Array addition Array subtraction Array multiplication Array right division Array left division Array exponentiation Form A + b A – b A + B A – B A.*B A./B A.\B A.^B 2-32

42 Array or Element-by-element multiplication is defined only for arrays having the same size. The definition of the product x.*y, where x and y each have n elements, is x.*y = [x(1)y(1), x(2)y(2),..., x(n)y(n)] if x and y are row vectors. For example, if x = [2, 4, – 5], y = [– 7, 3, – 8] (2.3–4) then z = x.*y gives z = [2(– 7), 4 (3), –5(–8)] = [–14, 12, 40] 2-33

43 If x and y are column vectors, the result of x.*y is a column vector. For example z = (x’).*(y’) gives Note that x’ is a column vector with size 3 × 1 and thus does not have the same size as y, whose size is 1 × 3. Thus for the vectors x and y the operations x’.*y and y.*x’ are not defined in MATLAB and will generate an error message. 2(–7) 4(3) –5(–8) –14 12 40 = z = 2-34

44 The array operations are performed between the elements in corresponding locations in the arrays. For example, the array multiplication operation A.*B results in a matrix C that has the same size as A and B and has the elements c i j = a i j b i j. For example, if then C = A.*B gives this result: A = 11 5 –9 4 B = –7 8 6 2 C = 11(–7) 5(8) –9(6) 4(2) = –77 40 –54 8 2-35 More? See pages 87-88.

45 The built-in MATLAB functions such as sqrt(x) and exp(x) automatically operate on array arguments to produce an array result the same size as the array argument x. Thus these functions are said to be vectorized functions. For example, in the following session the result y has the same size as the argument x. >>x = [4, 16, 25]; >>y = sqrt(x) y = 2 4 5 2-36

46 However, when multiplying or dividing these functions, or when raising them to a power, you must use element-by-element operations if the arguments are arrays. For example, to compute z = (e y sin x) cos 2 x, you must type z = exp(y).*sin(x).*(cos(x)).^2. You will get an error message if the size of x is not the same as the size of y. The result z will have the same size as x and y. 2-37 More? See pages 89-90.

47 Array Division The definition of array division is similar to the definition of array multiplication except that the elements of one array are divided by the elements of the other array. Both arrays must have the same size. The symbol for array right division is./. For example, if x = [8, 12, 15] y = [–2, 6, 5] then z = x./y gives z = [8/(–2), 12/6, 15/5] = [–4, 2, 3] 2-38

48 A = 2420 – 9 4 B = –4 5 3 2 Also, if then C = A./B gives C = 24/(–4) 20/5 –9/3 4/2 = –6 4 –3 2 2-39 More? See pages 91-92.

49 Array Exponentiation MATLAB enables us not only to raise arrays to powers but also to raise scalars and arrays to array powers. To perform exponentiation on an element-by-element basis, we must use the.^ symbol. For example, if x = [3, 5, 8], then typing x.^3 produces the array [3 3, 5 3, 8 3 ] = [27, 125, 512]. 2-40

50 We can raise a scalar to an array power. For example, if p = [2, 4, 5], then typing 3.^p produces the array [3 2, 3 4, 3 5 ] = [9, 81, 243]. Remember that.^ is a single symbol. The dot in 3.^p is not a decimal point associated with the number 3. The following operations, with the value of p given here, are equivalent and give the correct answer: 3.^p 3.0.^p 3..^p (3).^p 3.^[2,4,5] 2-41 More? See pages 92-95.

51 Matrix-Matrix Multiplication In the product of two matrices AB, the number of columns in A must equal the number of rows in B. The row-column multiplications form column vectors, and these column vectors form the matrix result. The product AB has the same number of rows as A and the same number of columns as B. For example, 6 –2 10 3 4 7 9 8 –5 12 = (6)(9) + (– 2)(– 5) (6)(8) + (– 2)(12) (10)(9) + (3)(– 5) (10)(8) + (3)(12) (4)(9) + (7)(– 5) (4)(8) + (7)(12) 64 24 75 116 1 116 = (2.4–4) 2-42

52 Use the operator * to perform matrix multiplication in MATLAB. The following MATLAB session shows how to perform the matrix multiplication shown in (2.4–4). >>A = [6,-2;10,3;4,7]; >>B = [9,8;-5,12]; >>A*B ans = 64 24 75 116 1 116 2-43

53 Matrix multiplication does not have the commutative property; that is, in general, AB  BA. A simple example will demonstrate this fact: AB = 6 –2 10 3 9 8 –12 14 = 78 20 54 122 (2.4–6) BA = 9 8 –12 14 6 –2 10 3 = 134 6 68 65 (2.4–7) whereas Reversing the order of matrix multiplication is a common and easily made mistake. 2-44 More? See pages 97-104.

54 Polynomial Roots The function The function roots(a) computes the roots of a polynomial specified by the coefficient array a. The result is a column vector that contains the polynomial’s roots. For example, >>r = roots([2, 14, 20]) r = -2 -7 2-50 More? See page 107.

55 Beware of using polynomials of high degree. An example of a fifth-degree polynomial that passes through all six data points but exhibits large excursions between points. Figure 5.6–4 5-77

56 Operations on Arrays MATLAB will treat a variable as an array automatically. For example, to compute the square roots of 5, 7, and 15, type >>x = [5,7,15]; >>y = sqrt(x) y = 2.2361 2.6358 3.8730 3-9

57 Expressing Function Arguments We can write sin 2 in text, but MATLAB requires parentheses surrounding the 2 (which is called the function argument or parameter). Thus to evaluate sin 2 in MATLAB, we type sin(2). The MATLAB function name must be followed by a pair of parentheses that surround the argument. To express in text the sine of the second element of the array x, we would type sin[x(2)]. However, in MATLAB you cannot use square brackets or braces in this way, and you must type sin(x(2)). 3-10 (continued …)

58 Expressing Function Arguments (continued) To evaluate sin(x 2 + 5), you type sin(x.^2 + 5). To evaluate sin(  x+1), you type sin(sqrt(x)+1). Using a function as an argument of another function is called function composition. Be sure to check the order of precedence and the number and placement of parentheses when typing such expressions. Every left-facing parenthesis requires a right-facing mate. However, this condition does not guarantee that the expression is correct! 3-11

59 Expressing Function Arguments (continued) Another common mistake involves expressions like sin 2 x, which means (sin x) 2. In MATLAB we write this expression as (sin(x))^2, not as sin^2(x), sin^2x, sin(x^2), or sin(x)^2 ! 3-12

60 Expressing Function Arguments (continued) The MATLAB trigonometric functions operate in radian mode. Thus sin(5) computes the sine of 5 rad, not the sine of 5°. To convert between degrees and radians, use the relation q radians = (p /180)q degrees. 3-13More? See pages 145-146.

61 User-Defined Functions The first line in a function file must begin with a function definition line that has a list of inputs and outputs. This line distinguishes a function M-file from a script M-file. Its syntax is as follows: function [output variables] = name(input variables) Note that the output variables are enclosed in square brackets, while the input variables must be enclosed with parentheses. The function name (here, name ) should be the same as the file name in which it is saved (with the.m extension). 3-18More? See pages 148-149.

62 User-Defined Functions: Example function z = fun(x,y) u = 3*x; z = u + 6*y.^2; Note the use of a semicolon at the end of the lines. This prevents the values of u and z from being displayed. Note also the use of the array exponentiation operator (.^ ). This enables the function to accept y as an array. 3-19 (continued …)

63 User-Defined Functions: Example (continued) Call this function with its output argument: >>z = fun(3,7) z = 303 The function uses x = 3 and y = 7 to compute z. 3-20 (continued …)

64 User-Defined Functions: Example (continued) Call this function without its output argument and try to access its value. You will see an error message. >>fun(3,7) ans = 303 >>z ??? Undefined function or variable ’z’. 3-21 (continued …)

65 User-Defined Functions: Example (continued) Assign the output argument to another variable: >>q = fun(3,7) q = 303 You can suppress the output by putting a semicolon after the function call. For example, if you type q = fun(3,7); the value of q will be computed but not displayed (because of the semicolon). 3-22

66 The variables x and y are local to the function fun, so unless you pass their values by naming them x and y, their values will not be available in the workspace outside the function. The variable u is also local to the function. For example, >>x = 3;y = 7; >>q = fun(x,y); >>x x = 3 >>y y = 7 >>u ??? Undefined function or variable ’u’. 3-23

67 Only the order of the arguments is important, not the names of the arguments: >>x = 7;y = 3; >>z = fun(y,x) z = 303 The second line is equivalent to z = fun(3,7). 3-24

68 You can use arrays as input arguments: >>r = fun([2:4],[7:9]) r = 300 393 498 3-25

69 A function may have more than one output. These are enclosed in square brackets. For example, the function circle computes the area A and circumference C of a circle, given its radius as an input argument. function [A, C] = circle(r) A = pi*r.^2; C = 2*pi*r; 3-26

70 The function is called as follows, if the radius is 4. >>[A, C] = circle(4) A = 50.2655 C = 25.1327 3-27

71 A function may have no input arguments and no output list. For example, the function show_date computes and stores the date in the variable today, and displays the value of today. function show_date today = date 3-28

72 1.One input, one output: function [area_square] = square(side) 2. Brackets are optional for one input, one output: function area_square = square(side) 3. Two inputs, one output: function [volume_box] = box(height,width,length) 4. One input, two outputs: function [area_circle,circumf] = circle(radius) 5. No named output: function sqplot(side) Examples of Function Definition Lines 3-29

73 Function Example function [dist,vel] = drop(g,vO,t); % Computes the distance travelled and the % velocity of a dropped object, % as functions of g, % the initial velocity vO, and % the time t. vel = g*t + vO; dist = 0.5*g*t.^2 + vO*t; 3-30 (continued …)

74 Function Example (continued) 1. The variable names used in the function definition may, but need not, be used when the function is called: >>a = 32.2; >>initial_speed = 10; >>time = 5; >>[feet_dropped,speed] =... drop(a,initial_speed,time) 3-31 (continued …)

75 Function Example (continued) 2. The input variables need not be assigned values outside the function prior to the function call: [feet_dropped,speed] = drop(32.2,10,5) 3. The inputs and outputs may be arrays: [feet_dropped,speed]=drop(32.2,10,[0:1:5]) This function call produces the arrays feet_dropped and speed, each with six values corresponding to the six values of time in the array time. 3-32More? See pages 148-153.


Download ppt "Matlab Review Exam 2 – Oct 28, 2009. Exam Reminders Open book. Only Matlab book, no notes or loose papers in book. Open book. Only Matlab book, no notes."

Similar presentations


Ads by Google