Anda di halaman 1dari 27

MECH2700: Mechanical Engineering Analysis I MATLAB

Introduction The C programming language is one focus of this course. The second focus is a programming environment called MATLAB. (The name is a portmanteau of matrix laboratory.). The strength of MATLAB is implicit in the name; it provides an environment for matrix calculations. This makes it extremely useful to engineers as matrices and vectors are nowadays the lingua franca for much engineering analysis. MATLAB is probably the most common tool used to engineering calculation for no other reason than it allows for easy expression of ideas phased within a matrix-vector formalism. In line with this, the emphasis of MATLAB component of this course is on matrix methods for numerical computation. The best source of information on MATLAB is probably the MATLAB help command and MATLAB manuals. You will find several MATLAB tutorials on the web including

http://www.maths.uq.oz.au/~gac/mlb/mlb.html http://www.math.ufl.edu/help/matlab-tutorial/matlab-tutorial.html http://www-csfy.cs.ualberta.ca/~c100/MLTutorial/ http://www.cz.nus.edu.sg/~lailf/matlab/tutorial.html http://www.indiana.edu:80/~statmath/math/matlab

The quality of these varies. The first comes from Dr Chandler in the UQ Maths Department and is very good MATLAB at Home Wondering what to do on Friday nights? The department has purchased 50 student licenses from CEANET, the Australian distributor of MATLAB which you can purchase and install on your home computer. The version you install has the full functionality offered by our Classroom License (including toolboxes). The cost of each license is $131. This is a considerable reduction in price over the commercial cost.

The Department's preference would have been for a third party to provide this service. CEANET was asked whether they would do this through the campus bookstore but they declined. They only make this option available through University Departments not Bookstores. You can buy MATLAB from CEANET over the internet, but it is much more expensive. In deciding whether to invest note, 1. Ownership is not compulsory. You have 24 hour access to MATLAB through the computer laboratory. 2. If you decide to purchase MATLAB through the Department, you will be asked to sign a License Agreement which will be forwarded to CEANET. 3. You are not allowed to on-sell this license. 4. You are not allowed to share your copy of MATLAB with another student 5. The license you will receive is perpetual but you can only use it for academic related work. 6. A public domain clone of MATLAB called Octave provides a reasonable substitute for MATLAB. A copy of this is available on 'MECH2700 Tools' CD which also includes the C compiler, the editor, and debugger. Octave is not as professional as MATLAB but you should be able to do most things using it. This 'MECH2700 Tools CD' is available through the Departmental Office. See Mrs. Valerie Hutchinson. You will be required to leave a small deposit ($5), refunded when you return the CD. 7. Any 'profits' returned by sale of MATLAB licenses go to the Student Formula SAE project. About these notes These notes are not a definitive account of MATLAB nor, indeed are they a definitive overview of the topics we discuss in this course. They are meant to cover a minimal subset of MATLAB necessary for our work and provide you with a framework for thinking about the topics discussed during lectures. You should aim to supplement the material we go over with reading from other sources. The right margin is deliberately wide to allow you to write extra comments during lectures, especially where you see the quill pen

The following icon indicates problems you can think-about outside of class.

Starting MATLAB On the Windows98 machines in 76-228 you can start MATLAB via the START button (Start->Programs->Applications for Mech Eng->MATLAB Release 12->Matlab R12.). This opens the MATLAB shell. You will see the MATLAB prompt. (>>). Getting Help in Matlab You will find you can get moving with MATLAB pretty quickly. Considerable information about all aspects of MATLAB is contained in the help files. A good place to start is by typing "help help". This will display the various options associated with the help command itself. . Linear simultaneous equations Many engineering problems involve solving sets of simultaneous equations Matrices and vectors provide a general and convenient notation in which to work. Consider, for example, the problem of analyzing the forces in the pin-jointed structure such in the figure below. 4 F24 F24 2 F23 F12 F14
W

F12 1

F14 F13

F13

F23

3
3

F11

F3 3

The thick lines represent the structural members. These meet at pinned nodes, indicated by circles and numbered 1 to 4. The arrows correspond to forces acting along the members. Resolving forces horizontally and vertically at each of the nodes gives a family of linear equations

Fij cos ij = 0,
j =1

F
j =1

ij

sin ij = 0.

where ij is the angle at which the force Fij between nodes i and j is applied and Fii denotes the external force applied to node i . Node 4 is distinguished from the other nodes in so far as it has an external force applied in the vertical direction W , which is known. The equations at node 4 can be reorganized with the known force W on the right hand side, i.e.

F
j =1

4j

cos 4 j = 0,

F
j =1

4j

sin 4 j = W .

Now, given the value of an externally applied force, such as the load W , on the structure, all other forces in the system can be calculated. It all boils down to solving a matrix equation of the form Ax = b where 0 0 1 cos 14 1 1 0 sin 14 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 cos14 0 0 0 sin 14 0 0 cos 23 sin 23 cos 23 sin 23 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 F11 0 F12 0 F13 0 F14 = 0 F23 0 F24 F 0 33 W

The nice thing about this formulation is that in principle the problem becomes no harder as you add more detail to the mechanical structure, extra bars and forces etc. The computer still solves the same form of equation
Ax = b .

This is in marked contrast to solving things on paper where, the larger the structure, the more equations there are and the harder it is for you to keep track of the arithmetic and come up with a correct answer. This is a great division of labor: your job is to understand the mechanical and mathematical principles, while the computer does the hard arithmetic graft. This powerful partnership has literally revolutionized Engineering Design methods. Another example showing how problems formulate naturally as Ax = b is the electrical network shown below

R13 R34 R12 Vin 2 R24 R02 4 Vout

This time the analysis proceeds by applying Kirchoff's law systematically to the numbered network nodes. Again this can be written out neatly using the node indexes: V j Vi = 0, i = 2,3,... Rij j i Those equations are all 'homogeneous', i.e. of the form 'Something' = 0 . An additional 'inhomogeneous' equation describes the input relation: V1 V0 = Vin Now, with Vin regarded as fixed, simultaneous equations of the form
Ax = b

can be solved to find all other voltages in the network, and then the output voltage Vout = V4 - V0 can be calculated. In this case x = (V0 , V4 )T b = (0, 0, 0, Vin )T and A is a matrix of conductances, whose elements are
1 appropriate sums of the Rij .

The form Ax = b occurs often enough that we give it a special name. We call it the Ax = b problem. The problem is to determine the elements of the vector x given the matrix A and the vector b . You should have come across it in the MT250 subject taught by the mathematics department. Hopefully the material we're going to cover will augment your understanding.

In the case where Amn is square (i.e. m == n ) and of full rank, a unique solution for x will exist. It is, however, evident from the examples above that in the general case it may be necessary to handle matrices that are rectangular - either landscape or portrait. Portrait: if n < m there are more equations than unknowns. There are two possibilities. Either the equations are inconsistent and there is no exact solution, in which case it may be desirable to look for the 'optimal' solution that most nearly satisfies the equations. Or else it may be that there is some redundancy in the equations set (for example, one equation might simply be a multiple of the other) allowing a unique solution to be found. Landscape: if n > m there are more unknowns than equations so that, rather than just one solution there is very likely a whole family of possible solutions. You will hopefully recognize these two situations from MT250. Here we will focus on the situations where m n , i.e. problems for which there exists a unique solutions and those for which we seek an 'optimal' solution. Before looking in more detail at Ax = b we'll briefly introduce some MATLAB basics. Consult the on-line manuals or the web tutorials above for more comprehensive descriptions.

MATLAB and matrix calculations You need only a small number of commands to start using MATLAB. The most important thing to keep in mind is: All MATLAB variables are matrices. Scalars, for instance, are matrices having one row and one column. Vectors have n-rows and 1-column. A general matrix has m-rows and n-columns, i.e. a11 ! a1n A= " # " a m1 $ amn with the element in the i-th row and j-th column written as aij or A(i, j ) . This index scheme, with the row given first and the column second, is known as row-column notation.

Suppose we have a matrix

1 2 3 A = 2 1 2 3 2 1

We enter can enter it at the MATLAB prompt (>>) as follows A = [1, 2, 3; 2, 1, 2; 3, 2, 1] If this line is followed by striking the 'enter' key, the computer will display the result for A. Generally, MATLAB prints out the result of computation after each line is entered. This printing can be suppressed by ending a line with a semicolon (;). Note that Matrices are entered between square brackets, i.e. []. Successive rows are separated by semicolons (or by entering on successive lines) Elements in a row are separated by commas (or blank spaces). MATLAB variables The C-programming language is 'strongly typed' by which is meant if you intend to use a variable, you must first declare it. You have give both a name by which you reference the variable and the 'type of data' that is to be contrained within that, e.g. int, long, float, double, char, char *, etc. MATLAB is less rigid. You can declare variables as and when they are needed. This flexibility is a consequence of the basic design of MATLAB. Formally we can describe MATLAB as a stack based interpreter by which we mean expressions are interpreted, evaluated, and put into a form that the CPU can understand (machine language) from a stack at run time. This contrasts with a compiled language where the expressions making up a program are converted into machine language at compile time. Compilation necessitates closer specification of data types so that the program is laid down appropriately in memory. We need to know up front what sort of data the program is to manipulate. The advantage of compilation is, in a word, speed. Compiled programs run faster than interpreted programs. Why then use interpreters. In a phrase, 'ease of use'. This 'ease of use' manifests itself most directly through the ease with which quick and dirty calculations can be performed. (This distinction between compilers and interpreters lies outside the course. If it interests you, you might like to look at 'The Unix Programming

Environment' by Kernighan and Pike, Prentice-Hall. This book gives full source code for an interpreter, called hoc, written in C.) Like C, MATLAB provides a variety of data types (type 'help datatypes') and 'overload methods'. For what we do in this course, we really only need to know about two types of data: doubles and strings. (The other data types and their associated overload methods are most useful when importing or exporting data in specific formats.) By default, you get a double whenever you enter a numeric value. For instance the MATLAB command a = 1.0 allocates space for a double precision variable called a and allocates asigns the value 1.0 to it. Complex numbers are handled seamlessly. For instance, we can create a complex valued variable b=1+i2 by entering b = 1+2i MATLAB's response is to allocate space for a double precision complex number - effectively two double precision numbers - and assign to it the appropriate value. Earlier we entered a matrix

A = [1, 2, 3; 2, 1, 2; 3, 2, 1] Here MATLAB allocates space for a 3x3 matrix of doubles and assigns values to the elements appropriately. And so on. Strings contain text and are entered by enclosing text between single quotes. (Note the distinction with C where double quotes are used). For example str = 'This is a string' creates space for and assigns the given text to the variable str. In line with the ideas that all MATLAB variables are matrices, we can have matrices of strings. Computations in MATLAB When you ask MATLAB to execute a computation, for instance multiply two variables, you are implicitly instructing a matrix multiplication. Similarly for addition and subtraction. The results MATLAB returns from such computations are also, naturally, matrices. The sizes of these matrices

(i.e. number of rows and columns) must, of course, be compatible you cannot multiply a 5x6 matrix with a 2x1-vector but they can be arbitrarily large subject to the amount of memory available on the computer. There is one exception to the requirement that operands be compatibile. Just as in ordinary matrix algebra, we can multiply/divide any matrix by a scalar (a 1x1-matrix). When we do so it is implicit that we are multiplying/dividing each element of a the matrix by the scalar. In summary: In MATLAB the elementary operators (*,+,-, \ are matrix operators. The operators +, -, and * are all straightforward enough. The divide operator has its usual meaning when applied to scalars or a scalar and a matrix, but it's a bit more complex when applied to matrices. You can, if you like, think of a matrix divide as involving a matrix inversion. Matrix divides come in two forms: a left divide (\) and a right divide (/). Specifically A \ B is the matrix division of A into B, which is roughly the same as A1 B . If A is a n n matrix and B is column vector with n components, or a matrix with n rows, then MATLAB doesnt bother computing the inverse of A . Rather it computes the result directly via Gaussian elimination. (which you covered in MT250). A right matrix division A / B is the matrix division of B into A , i.e. AB 1 . Type 'help mldivide' and 'help mrdivide' for more information about left and right matrix division. I'll add that these matrix divider operators are mentioned more in passing, rather than as a fundamental part of the course, i.e. you won't be examined on your ability to recall this particular part of the matlab syntax. Precedence Mathematical expressions are evaluated from left to right using the usual precedence rules, i.e. Precedence level 0 1 2 Operator +, *, /, \ ^ (power)

You can use parentheses to 'alter' the precedence rules, in the same way as you would in normal algebra and the C programing language.

10

To illustrate basic MATLAB operations, here's a sample session (including output) as demonstration. The lines beginning with '%' are comments.

% Create an identity matrix. >> E = [1, 0, 1; 0, 1, 0; 0, 0, 1] E = 1 0 0 0 1 0 1 0 1

% Create a vector u picks out the first column from E. % In Matlab matrices are defined in row column form. >> u=E(:,1) u = 1 0 0 % Change E >> E(3,1)=5 E = 1 0 5 0 1 0 1 0 1

assigns the value 5 to the element in row 3 column

% Multiply Eu the command E*u multiplies E and u >> v = E*u v = 1 0 5

Some things to note when trying to decipher this example Variables a and A are different; MATLAB is case sensitive. Unlike the C language, in MATLAB you don't need to predefine matlab variables. They are created on demand. Variable names must begin with a letter, contain only letters and digits, and be no longer than nineteen characters long. (You can enter longer names but MATLAB retains only the first nineteen characters.) MATLAB works in contexts called workspaces. Think of them like blank sheets of paper on (in?) which you can enter manipulate variables. When you start MATLAB you are working in the command prompt workspace. This idea of workspaces is important when we come to look at writing functions in MATLAB. Specifically each function operates in

11

its own workspace. Variables defined in one workspace are not in general visible in other workspaces. Entering the command who or whos at the displays the names of all variables in the command prompt workspace. The command clear var removes the user defined variable var (if it exists) from the current MATLAB workspace. The command clear (on its own) removes all MATLAB variables from the current MATLAB workspace. If an arithmetic expression is entered alone (not part of an assignment statement) , the value of the expression is returned in the variable ans. The word help followed by a MATLAB symbol or command name gives help on that topic. E.g. 'help mtimes' gives help on matrix multiplication. Typing 'helpdesk' starts the on-line documentation (in a HTML viewer). Placing a semicolon after the command name stops MATLAB displaying the result of a computation to the screen. Within the MATLAB shell, use the up-arrow cursor to return to previous commands.

A very brief overview of MATLAB syntax . Ways to input a row or column vector
u = [2, 4, 5]

has one row with three components (a row vector, equally a 1x3-matix) v= [2; 4; 5] has three rows with one column note the semicolons (a column vector, equally 3x1 matrix). v = [2, 4, 5]' or v = u' transposes u to give v. w = 2:5 generates the row vector w = [2, 3, 4, 5] with unit steps. x = 1:2:7 generates the row vector x = [1, 3, 5, 7] from 1 to 7 in steps of 2.

Ways to input a matrix A = [1, 2, 3; 4, 5, 6] has two row, each with three elements (again the semicolon indicated the end of a row) gives the same matrix but takes longer to type in. A = [1, 2, 3 is the transpose of A. That is the transpose of a matrix in MATLAB is effected by following the matrix with an apostrophe.
4, 5, 6] B = [1, 2, 3; 4, 5, 6]'

12

Modifying the elements of a matrix A


A(3,2) = 7

sets or reset the element of A located at row 3, column 2 to

7. resets the third row equal to v. resets the second column equal to w. The colon (:) symbol when used in indexing a matrix stands for all: all columns or
A(3,:) = v A(:,2) = w all rows A([2,3],:) = A([3,2],:)

exchanges rows 2 and 3 in A.

Creating sub-matrices from an nxm matrix A A(i,j) returns the (i,j)-th entry of matrix A as a 1x1 matrix (a scalar). returns the i-th row as a row vector. A(i,:) returns the j-th column as a column vector A(:,j) A(2:4,3:7) returns the sub-matrix spanning rows 2 to 4 and columns 3 to 7. A(4:6,:) returns a 3 times n matrix containing rows 4 through 6. A(:) returns on long column vector formed by concatenating all the columns of A. Concatenating matrices B= [A,A] produces B= 123123 456456 That is, the matrix B is formed as two copies of the matrix A placed side-byside. Matrices can also be joined on top of each other, provided they have the same number of columns. Some cautions when entering matrices in MATLAB In a string of numbers, a blank space is interpreted to be the same as a comma, i.e. a separator of numbers. The number 4.2 103 is entered 4.2e-3 (no spaces). The number 103 is entered as 1e-3, not e-3. The latter would be interpreted as a variable 'e' minus the number '3'. Some built in MATLAB matrix functions MATLAB has a number of built in functions to that simplify the process of entering and manipulating matrices. More information on these functions can be obtained with the help command.

13

Matlab function length(x) size(A) zeros(n) ones(n) ones(m,n) ones(size(A)) eye(n) eye(m,n) diag(x)

Returns
If x is a vector, returns the length of that vector. If x is a matrix returns the largest of the number of rows and columns. For a matrix A returns a 1 x 2 row vector containing the size of the matrix A An nxn matrix whose elements are all zero. An nxn matrix whose elements are all ones An mxn matrix whose elements are all ones. A matrix of all ones of the same size as A An nxn identity matrix An mxn matrix with ones on the principle diagonal and zeros elsewhere If x is a vector of length n, diag(x) is an nxn matrix with the values of x along the diagonal.

1. Predict the output of the following MATLAB statements x = 1:4 y=4:-1:1 A = [x;y] A=[A;A] 2. A = [1:4;2:5;3:6;4:7] 3. theta = 0:0.1:pi x = sin(theta) y = cos(theta) z = tan(theta) table = [theta; x, y, z]';

14

Loop structures in MATLAB Suppose we want to calculate the polynomial y ( x ) = c1 x n + c2 x n1 + $ + cn x + cn +1 at some value of x . An algorithm to do this is given by the following x (some value of x) Step no. 1. y cn+1 2. 3. " n +1 y y + c1 x n (The arrow notation indicates the value of the expression on the right is evaluated and placed in the variable on the left. ) We can implement this calculation in MATLAB using the 'for' loop. The MATLAB for loop is conceptually similar to the C-language for loop although it differs in notation. For loops The for loop executes a statement of group of statements a predetermined number of times. for index = start: increment: end statements end y y + cn x y y + cn1 x 2

An example is

for i = 1:1:10 fprintf('i = %d\n', i) end This produces output i = 1

15

i i i i i i i i i

= = = = = = = = =

2 3 4 5 6 7 8 9 10

This looks a lot like 'C'; you might think life would be a lot simpler if the designers of MATLAB had copied the C-syntax and be done with it. In fact, something more subtle is going on here. The text immediately following for , i.e. i = 1:1:10 Defines a vector
i= 1 2 3 4 5 6 7 8 9 10

The for loop replaces i successively by the elements of this vector. The more general form of the for-loop is for i = matrix expression matlab statements end which proceeds by replacing i successively by the columns of the matrix expression. Thus in addition to the usual situation where i is a numerical counter we can, in MATLAB, develop more elaborate loops in wherein the loop counter could be a sequence of vectors. Suppose we wish to evaluate the polynomial y ( x ) = 2 x5 + 5 x 4 x 3 + 2 x + 1 at x = 2.0 . Following the algorithm above, we could do this with the following MATLAB code c = [2, 5, -1, 0, 2, 1]; n = length(c); x= 2.0;

16

y = 0; for i = 1:n y = y+c(i)*x^(n-i); end fprintf('y(%f) = %f\n', x, y);

Note how we've expressed the coefficients in a vector c and used the length operator to get the size of this vector. Running this code produces the output
y(2.000000) = 141.000000

A more efficient algorithm The method for polynomial evaluation used above is correct but it is inefficient because we repeatedly compute powers of x . A more efficient algorithm evaluating polynomials is Horner's method. The basis for the method is to regroup our polynomial as follows y( x) =

((((2 x + 5) x 1) x + 0 ) x + 2) x + 1

We could express this computation in MATLAB as c = n = x = y = for [2, 5, -1, 0, 2, 1]; length(c); 2.0; c(1); i = 2:n y = y*x + c(i);

end fprintf('y(%f) = %f\n', x, y);

Nested for loops and plots Suppose we wanted to evaluate the polynomial at a number of values of x so that the function might be plotted. We could do this by nesting two 'for' loops, one iterating on values of x and the other evaluating the polynomial as above. MATLAB has a plot function that allows us to plot two variables against one another. Suitable matlab code is given below.

17

c n x m

= = = =

[2, 5, -1, 0, 2, 1]; length(c); -3:0.1:3; length(x);

for j = 1:m y(j) = c(1); for i = 2:n y(j)= y(j)*x(j)+c(i); end end plot(x,y); The nested for loop generates a vector containing the values of y corresponding to the values in our vector x. The plot function plots x against y in a `figure window' producing the graphical output shown below. (The MATLAB plot function produces takes a variety of arguments - type 'help plot' at the MATLAB command prompt to learn more). y
900 800 700

y ( x) 600
500 400 300 200 100 0 -100 -3 -2 -1 0

18

Vectorized calculations ; element by element operators. While the previous examples is illustrative of nested for loops, MATLAB offers certain notational efficiencies that can further simplify the code above. Specifically we can 'vectorize' the calculations by making use of element-by-element operators. To help with this MATLAB has an 'array mulriplication' operator that implements element-by-element multiplication is designated by '.*', i.e. a dot (.) followed by a star (*). To illustrate array multiplication consider the following vectors x = [1, 2, 3] y = [3, 0, 1]; The element by element multiplication operator allows us to multiply individual elements together, i.e. x .*y = [1*3, 2*0, 3*1] = [3, 0, 3]. Note that the two vectors x and y must have the same dimension. (For more information on array multiplication, type 'help times' at the MATLAB prompt). Using the element-by-element matrix operator we can rewrite our polynomial evaluation code in simpler form as. c = n = x = y = for [2, 5, -1, 0, 2, 1]; length(c); -3:0.1:3; c(1)*ones(1, length(x)); i = 2:n y= y.*x +c(i);

end plot(x,y); Note in particular the line y= y.*x +c(i); This multiplies each element of the vector y by the corresponding value in the vector x. The value of c(i)(which is a scalar), is then added to the

19

resulting vector and the result placed in the vector y (in so doing, we overwriting the previous values stored in the vector y). Another element by element operations that may be useful is the array power operator. Here Z = X.^Y denotes element-by-element powers matrices X and Y. These matrices must have the same dimensions (unless one is a scalar.)

Matlab scripts and functions; m-files It becomes tedious typing several lines of MATLAB over and over again. Where we have series of calculations we perform several times we can embed them in either a MATLAB script or a MATLAB function (A MATLAB function is the analog of a function in the C-programming language; C does not have an equivalent to MATLAB scripts). Both scripts and functions are stored in files given a '.m' postfix and this reason they go by the name m-files. (Giving the functions a '.m' postfix serves to tell MATLAB they are MATLAB files). Scripts are self-contained collections of MATLAB commands collected together and given a name. We could, for instance, put our code for evaluating the polynomial in a script. To create a script to execute the vectorized version of our polynomial evaluation do the following. 1. On the pull-down menus go to 'file->new->m-file'. This will open the MATLAB editor/debugger. 2. Enter the text 3. Save the file via the pull-down menus 'file->save-as'. This saves the entered text in an m-file. 4. Run the script by typing the name of the script (as specified in the previous step) from the MATLAB prompt. MATLAB functions allow you to extend the built in function library with functions of your own. Like C-functions, MATLAB functions accept input and return output. MATLAB functions operate on variables in their own workspace. This is separate from the workspace you see at the MATLAB prompt with the consequence that any information you wish to pass to a MATLAB function must be passed via arguments to that function.

20

To create a MATLAB function, proceed in the same way as for a script, bringing up the editor/debugger. All MATLAB functions begin with a header statement of the form function [output] = function_name(arguments) This is followed by appropriate matlab commands. For instance, the problem of polynomial evaluation might be encoded in the following function.

function y = evalpoly(c, x) % EVALPOLY - polynomial evaluation % % If c is a vector whose elements are the % coefficients of a polynomial, then % evalpoly(c,x) is the value of the polynomial % evaluated at x. [m,n] = size(x); nc = max(size(c)); y = zeros(m,n); for i=1:nc y = x.*y+c(i)*ones(m,n); end To call a MATLAB function we enter the function name at the MATLAB prompt together with appropriate arguments.

1. Confirm this function works by first entering and saving the function as an m-file (called evalpoly) and then typing at the MATLAB prompt y = evalpoly(c,x);

2. What happens when you type 'help evalpoly' at the MATLAB prompt?

21

3. The example above shows how to enter functions that accept multiple arguments. Explore the creation of functions that return multiple arrays of results. (Hint try typing 'help function'). Logical structures in MATLAB A logical operation distinguishes a statement as being true or false. For instance, the statement a < b is true if the quantity stored in a is less than that store in b; otherwise it is false. You will be familiar with logical operations from your understanding of the C programming language. Logical operations in MATLAB are constructed from comparisons between various quantities with symbols effecting the comparison called relational o operators. As in C, logical expressions in MATLAB evaluate to true or false. In MATLAB true has a numerical value of +1 and false has the value zero. The MATLAB relational operators are summarized in the table below. Relational operator < <= > >= == ~= Meaning Less than Less than or equal to Greater than Greater than or equal to Equal Not equal

In contradistinction to the logical operators of the C programming language, MATLAB relational operators can be applied to matrices as well as simple scalars. (Of course we should expect this; remember every MATLAB variable is a matrix). When they are applied to matrices, the relational operators compare corresponding elements returning a matrix of the same size containing zeros and ones as appropriate to the comparison. That is, relational operators dont compare matrices as a whole, but rather compare them on an elementby-element basis. Any two matrices so compared must, of course, be of the same size. To help in understanding this statement consider the following: >> a = [1, 2; 3, 4]; >> b= [5, 6; 1, 0];

>> a < b ans =

22

1 0 >> a == b ans = 0 0

1 0

0 0

What will the following logical relations evaluate to u = [1 0 2; 3 0 5] v = [3 2 1; 0 0 6]

u u u u

< v == v > v <= v

In addition to relational operators, MATLAB provides logical operators that can be used to combine expressions. The combinatorial operators evaluate all nonzero operands as true, i.e. +1 and returning either true or false. The combinatorial operators are Logical operators & | ~ Meaning AND OR NOT

Logical AND and OR operations takes the general form operand1 logical_operator operand2 For example, An expression using the AND (&) operator is true if both operands are logically true.

23

An expression using the OR (|) operator is true if one of the operands is logically true.

The general form of the NOT operator is ~operand The NOT operator negates the operand. If the operand is true (non zero), applying the NOT operator evaluates to false (zero). Vice versa if the operand is false.

What do the following evaluate to? u = [ 1 0 2 3 0 5] v = [5 6 1 0 0 7] u & v u | v ~u Logical and relational operators can be combined. MATLAB applies the following rules when evaluating such expressions 1. A logical expression is evaluated by first processing all arithmetic expressions. Then logic operators are processed by scanning from left to right. For instance a = 1; b = 2; c = 4; a + b > c Is evaluated as 3 > 4 Which is false, and hence evaluates to zero.

2. Subexpressions are combined from left to right with &s processed before |s. E.g. (a == b) | (x < 1) & (z >=0) has the same meaning as

24

(a == b) | ((x < 1) & (z >=0))

3. A relational operator like a < b is valid only if the two matrices a and b have the same size. An exception is the comparison of a matrix with a scalar. Sclars can always be compared with matrices or other scalars.

Flow control: If, else, and elseif The MATLAB 'If' directive evaluates a logical expressions and executes a group of statements based on the value of the expression. The form of the if structure is if logical_expression statements end The statements between the if and end are executed if logical expression evaluates to true (+1). The 'else' and 'elseif' statements allow us to add further conditions to an if statement. The else statement has no logical condition associated with it. The elseif statement has a logical condition associated with it. The general syntax is if logical_expression_1 statements_1 elseif logical_expression_2 statements_2 . . . elseif logical_expression_n statements_n else statements_n+1 end Here statements_1 is executed only if logical_expression_1 is true; statements_2 is executed only if logical_expression_1 is

25

false and logical_expression_2 is true; and so on. If none of the logical expressions evaluates to true, statements_n+1 is executed. While loops The while loop executes a group of statements as long as the controlling expression is true (i.e. non-zero). The syntax is while expression statements end

Break; return; error. It is common practice to use an 'if' construct as a test within a for or while loop to monitor the progress of a calculation. For instance we may desire to test when some tolerance is reached, or equally when there is evidence that the computation is diverging so that execution of the loop may be terminated. MATLAB has commands break, return (analogous to Ccommands of the same name), and error to terminate computations within for and while loops. break - Terminates a for or while loop. Where loops are nested, break terminates the innermost loop in which it is placed return - causes a normal return from a function from the point at which return is called. It is similar to the return statement in 'C'. error('text string') . Terminates execution and displays the message contained in text string

Example: Computing machine epsilon. To see how these programming constructs are used let us start with a problem you're familiar with from earlier in the course: calculating the order of the smallest flowing point number such that 1.0 + > 1.0 . Having access to is useful in interpreting the results of a numerical computation. It is also useful in deciding the smallest tolerance to use for terminating iterative loops. The following MATLAB code finds an approximation that differs from the true value of by no more than a factor of 2 and illustrates the use of an if statement to break out of a while loop.

26

epsilon = 1.0; while 1 eps_temp = epsilon / 2.0; if 1.0 + eps_temp == 1.0 break end epsilon = eps_temp end fprintf('epsilon = %e\n', epsilon); When run on my office PC the following output is produced. epsilon = 2.220446e-016

27

Anda mungkin juga menyukai