matlab review exam 2 – oct 28, 2009. exam reminders open book. only matlab book, no notes or loose...

Post on 11-Jan-2016

235 Views

Category:

Documents

5 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Matlab ReviewMatlab Review

Exam 2 – Oct 28, 2009Exam 2 – Oct 28, 2009

Exam RemindersExam Reminders

Open book. Only Matlab book, no notes or Open book. Only Matlab book, no notes or loose papers in book.loose papers in book.

Bring pen, calculator, and ruler.Bring pen, calculator, and ruler. Arrive on timeArrive on time Leave backpacks, cellphones etc along Leave backpacks, cellphones etc along

the wallsthe walls Skip a chair between you and the next Skip a chair between you and the next

personperson Paper and stapler will be providedPaper and stapler will be provided

Important TopicsImportant Topics

Figuring out answer for given Matlab Figuring out answer for given Matlab commands or scriptscommands or scripts

Polynomials: evaluating them, plotting Polynomials: evaluating them, plotting them, determining min or max or rootsthem, determining min or max or roots

Writing a Matlab script to solve a given Writing a Matlab script to solve a given engineering problemengineering problem

Writing scripts for functionsWriting scripts for functions

Good Slides to Good Slides to ReviewReview

Extracted from all chapter slidesExtracted from all chapter slides

Scalar Arithmetic Operations Table 1.1–1

1-51-5

Symbol Operation MATLAB form

^ exponentiation: ab 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

Order of Precedence Table 1.1–2

1-61-6

Precedence Operation

First Parentheses, evaluated starting with the innermost pair.

Second Exponentiation, evaluated from left to right.

Third Multiplication and division with equal precedence, evaluated from left to right.

Fourth Addition and subtraction with equal precedence, evaluated from left to right.

Examples of Precedence

>> 8 + 3*5ans = 23>> 8 + (3*5)ans = 23>>(8 + 3)*5ans = 55>>4^2 12 8/4*2ans = 0>>4^2 12 8/(4*2)ans = 3

1-71-7 (continued …)

Examples of Precedence (continued)

>> 3*4^2 + 5ans = 53>>(3*4)^2 + 5ans = 149>>27^(1/3) + 32^(0.2)ans = 5>>27^(1/3) + 32^0.2ans = 5>>27^1/3 + 32^0.2ans = 11

1-81-8

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 formulaw = 5 sin u 101 times.

1-151-15

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-161-16 More? See pages 19-20.

Polynomial Roots

To find the roots of x3 – 7x2 + 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-171-17

Solution of Linear Algebraic Equations

6x + 12y + 4z = 707x – 2y + 3z = 52x + 8y – 9z = 64

>>A = [6,12,4;7,-2,3;2,8,-9];>>B = [70;5;64];>>Solution = A\BSolution = 3 5 -2

The solution is x = 3, y = 5, and z = –2.

1-261-26 More? See page 28.

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, or2. 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-271-27 More? See pages 29-32.

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-281-28

Input/output commands Table 1.4–2

1-351-35

Command Descriptiondisp(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.

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 ≤ tf, where tf is the final time entered by the user.

1-361-36(continued …)

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

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

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-391-39 More? See pages 37-38.

Relational operators Table 1.6–1

1-441-44

Relational Meaning

operator

< Less than.<= Less than or equal to.> Greater than.>= Greater than or equal to.== Equal to.~= Not equal to.

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-451-45 More? See pages 44-45.

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-461-46

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-471-47 More? See pages 45-46.

The if Statement  The general form of the if statement is 

if expressioncommands

elseif expressioncommands

elsecommands

end 

The else and elseif statements may be omitted if not required.

1-481-48

1-491-49

Suppose that we want to compute y such that

15√4x + 10 if x ≥ 910x + 10 if 0 ≤ x < 910 if x < 0

The following statements will compute y, assuming that the variable x already has a scalar value.if x >= 9y = 15*sqrt(4x) + 10

elseif x >= 0y = 10*x + 10

elsey = 10

endNote that the elseif statement does not require a separate end statement.

y =

More? See pages 47-48.

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

You can also create a column vector by separating the elements by semicolons. For example,

>>g = [3;7;9]g = 3 7 9

2-42-4

2-52-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].

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-62-6

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

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.

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-132-13

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-142-14

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.

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

You can use array indices to extract a smaller array from another array. For example, if you first create the array B

B =

2-172-17

C =16 3 7 8 4 9

2 4 10 1316 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.

Array Addition and Subtraction

6 –210 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+Bans = 15 6 -2 17

For example:

2-272-27

(2.3-1)

More? See page 85.

Multiplying a matrix A by a scalar w produces a matrix whose elements are the elements of A multiplied by w. For example:

32 95 –7

= 6 2715 –21

This multiplication is performed in MATLAB as follows:

>>A = [2, 9; 5,-7];>>3*Aans = 6 27 15 -21

2-292-29

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-302-30

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

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-322-32

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-332-33

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)

–141240

=z =

2-342-34

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 ci j = ai j bi 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-352-35 More? See pages 87-88.

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-362-36

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 = (ey sin x) cos2x, 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.

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-382-38

A = 24 20– 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.

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 [33, 53, 83] = [27, 125, 512].

2-402-40

We can raise a scalar to an array power. For example, if p = [2, 4, 5], then typing 3.^p produces the array [32, 34, 35] = [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.^p3.0.^p3..^p(3).^p3.^[2,4,5]

2-412-41 More? See pages 92-95.

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-422-42

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*Bans = 64 24 75 116 1 116

2-432-43

Matrix multiplication does not have the commutative property; that is, in general, ABBA. A simple example will demonstrate this fact:

AB = 6 –210 3

9 8–12 14

= 78 2054 122

(2.4–6)

BA = 9 8–12 14

6 –210 3

= 134 6 68 65 (2.4–7)

whereas

Reversing the order of matrix multiplication is a common and easily made mistake.

2-442-44 More? See pages 97-104.

Polynomial RootsPolynomial Roots

The functionThe 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.

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-775-77

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-93-9

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-103-10(continued …)

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-113-11

Expressing Function Arguments (continued)

Another common mistake involves expressions like sin2 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-123-12

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 qradians = (p /180)qdegrees.

3-133-13 More? See pages 145-146.

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-183-18 More? See pages 148-149.

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-193-19 (continued …)

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-203-20

(continued …)

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-213-21

(continued …)

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-223-22

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 workspaceoutside the function. The variable u is also local to the function. For example,

>>x = 3;y = 7;>>q = fun(x,y);>>xx =3

>>yy =7

>>u??? Undefined function or variable ’u’.

3-233-23

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-243-24

You can use arrays as input arguments:

>>r = fun([2:4],[7:9])r = 300 393 498

3-253-25

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-263-26

The function is called as follows, if the radius is 4.

>>[A, C] = circle(4)A =50.2655

C =25.1327

3-27

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_datetoday = date

3-28

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-293-29

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 …)

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 …)

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-32 More? See pages 148-153.

top related