Vous êtes sur la page 1sur 14

De La Salle University Electronics and Communications Engineering Department Matlab Fundamentals Laboratory Experiment 1 I. Objectives : [1.

] To be able to familiarize with some of the commands and capabilities of MATLAB. [2.] To be able to learn how to do Matrix/Vector manipulation, complex algebra, and graphics in MATLAB II. Introduction Matlab is a technical computing environment for high-performance numeric computation and visualization. Matlab integrates numerical analysis, matrix computation, signal processing, and graphics in an easy-to-use environment where problems and solutions are expressed just as they are written mathematically-without traditional programming. Matlab can be started by entering matlab at the system prompt or by clicking on the MATLAB icon, depending on the machine you are using. Once invoked, MATLAB will clear the screen, provide some introductory remarks, and produce the MATLAB prompt >>. To quit MATLAB, type quit or exit followed by carriage return key. 2.1 Fundamental expressions Working with the MATLAB environment is straightforward because most commands are entered as you write them mathematically. 2.1.1 Variable

Expression typed without a variable name are evaluated by MATLAB and the result is stored and displayed by a variable called ans. The result of an expression can be assigned to a variable name. Variable names can have as many as 19 characters (including letters and numbers). However, the first character must be a letter. Matlab is case sensitive. The command casesen makes MATLAB insensitive to the case. For example, entering the following expression

Matlab Fundamentals

Page 1

If you do not care to create a new variable but want to know the value of an expression, you can type the expression by itself, e.g.,

If you wish to create a new variable but do not want to see the MATLAB response, type a semicolon at the end of the expression. For example,

It will create a new variable a whose value is 7, but MATLAB will not display the value of a. The semicolon is very useful when large vectors or matrices are defined or computed in intermediate step of a computation. You can check the value of variable at any time by entering the variable name at the prompt. For example,

Matlab Fundamentals

Page 2

Notice that MATLAB display the result with 5 significant digits (default format: format short). The commands format short e, format long, and format long e display 5 digits floating point, 15 digits fixed point, and 15 digits floating point, respectively. For more flexibility in the output format, the command fprintf displays the result with a desired format on the screen or to specified filename. For example, the command

The %7.3f prints a floating point number at least 7 characters wide, with 3 digits after the decimal point . The sequence \n advances the output to the left margin on the next line MATLAB has several predefined variables. These are given in table 1-1 Table 1-1. Special Variables and Constants ans Most recent answer computer Computer Type Eps Floating point relative accuracy flops Count of floating point operations i,j Imaginary unit Inf Infinity NaN Not-a-Number nargin Number of function input arguments nargout Number of function output arguments Pi 3.1415926535897... realmax Largest floating point number realmin Smallest floating point number 2.1.2 Character String

A sequence of characters in single quotes is called a character string or text variable. Character string can be generated by s sequence of characters in single quotes. Example:

Matlab Fundamentals

Page 3

A text variable can be augmented with more text variable, for example,

2.2 Elementary Matrix Operation Matrices are entered into MATLAB by listing the elements of the matrix and enclosing them within a pair of brackets. Elements of a single row are separated by commas or blanks, and rows are separated by semicolons or carriage return. For example,

The entire row or column of a matrix can be addressed by means of the symbol (: ). For example,

Matlab Fundamentals

Page 4

Similarly, the statement A( : , 2) addresses all elements of the second column in A. Typing A( : ) will return all the elements of A. Matrices of the same dimension can be added or subtracted. Two matrices, A and B, can be multiplied together to form the product AB if they are comformable. A \ B is equivalent to A-1 B, and A/B is equivalent to A B-1. The inverse of a matrix can be obtained using the MATLAB function inv MATLAB has commands for generating special matrices. For example, you can create a diagonal matrix with the diag command using a vector containing the diagonal elements as the input argument, such as

Other special matrices that can be generated are given in table 1-2. Table 1-2. Elementary Matrices Eye Identity Matrix meshgrid X and Y arrays for 3-D plots Ones Ones matrix Zeros Zeros matrix Rand Uniformly distributed random numbers Randn Normally distributed random numbers Matrices can be manipulated using the following MATLAB functions given in Table 1-3. Also, shown in table 1-4 are some of the matrix functions in matlab Table 1-3. Matrix Manipulation Diag Create or extract diagonal fliplr Flip matrix in the left/right direction flipud Flip matrix in the up/down direction reshape change size rot90 Rotate matrix 90 degrees Tril Extract lower triangular part Triu Extract upper triangular part : Index into matrix, rearrange matrix
Matlab Fundamentals Page 5

Table 1-4. Matrix Functions det Determinant norm Matrix or vector norm trace Sum of diagonal elements inv Matrix inverse eig Eigenvalues and eigenvectors poly characteristic polynomial expm Matrix exponential logm Matrix logarithm sqrtm Matrix square root 2.3 Vector Operation A vector is either a row vector or a column vector with array of n numbers. In Matlab, elements enclosed by brackets and separated by semicolon generate a column vector. The transpose of a row vector is a column vector, and vice versa. This can be done in Matlab using the symbol ( ). For example, >> Y=R means Y is the transpose of a vector or matrix R. Vectors of the same size can be added or subtracted. The operation ( .* ) performs element-byelement multiplication. The ( : ) can also be used to generate a row vector. For example,

generates a row vector of integers from 1 to 8. For increment other than unity, the following command can be used:

Matlab Fundamentals

Page 6

For negative increment

2.4 Elementary Function Some of the Matlab function automatically operate element by element on an array. For example, exp(x) will return an array with each element equal to the exponential of the corresponding element of x. The other function that operate element by element are given in table 1-5. Table 1-5. Elementary Math Functions abs Absolute value acos Inverse cosine acosh Inverse hyperbolic cosine angle Phase angle asin Inverse sine asinh Inverse hyperbolic sine atan Inverse tangent atanh Inverse hyperbolic tangent conj complex conjugate cos Cosine cosh Hyperbolic cosine exp Exponential fix Round towards zero floor Round towards infinity imag Complex Imaginary part log Natural logarithm log10 Common logarithm real Complex real part rem remainder after division round Round towards nearest integer sign Signum function sinh Hyperbolic sine sqrt Square root tan Tangent tanh Hyperbolic tangent
Matlab Fundamentals Page 7

2.5 Data Structures in Matlab Data structures in MATLAB include the following: Multidimensional arrays, Cell arrays, Characters and text, and Structures 2.5.1 Multidimensional Array

Multidimensional arrays in MATLAB are arrays with more than two subscripts as shown below

2.5.2

Cell Array

A cell array is a Matlab array wherein elements are cell containers that can hold other Matlab array. For example, one cell of a cell array may contain a real matrix, an array of text string, or a vector of complex values. Cell arrays are created by enclosing a miscellaneous collection of things in curly braces, { }. The curly braces are also used with subscripts to access the contents of various cells. For example to Create a 2-by-2 cell array A with the following contents

Matlab Fundamentals

Page 8

Will correspond to the following expressions in Matlab

2.5.3

Characters and Text

Texts are entered in MATLAB using single quotes. For example, s = 'Hello' The result is not the same kind of numeric matrix or array. It is a 1-by-5 character array. Internally, the characters are stored as numbers, but not in floating-point format. The statement a = double(s) converts the character array to a numeric matrix containing floating-point representations of the ASCII codes for each character. The result is a = 72 The statement s = char(a) reverses the conversion. 2.5.4 Structures 101 108 108 111

Structures are Matlab arrays with named data containers called fields. The fields of a structure can contain any kind of data. For example, one field may contain a text string representing a name, another may contain a scalar representing a bill amount, a third may hold a matrix of medical results, and so on. For example:
Matlab Fundamentals Page 9

Patient.name=Juan de la Cruz Patient.billing=127.00 Patient.test=[79 75 73;180 178 177.5;220 210 205]

2.6 Logical Operators Matlabs relational operators and logical operators also work in an element-by-element basis. Relational operators compare two scalars and produce a 1 if the operation is true and a 0 if it is false. For example, if you enter t = 17 > 55, MATLAB will respond with t =0. When used with two matrices, relational operators compare corresponding matrix elements. For example, L = D < = X will check every element of D against the corresponding element of X. If the element of D is less than or equal to the corresponding element of X, the corresponding element of L will be 1. Otherwise, the corresponding element of L will be zero. The logical operators & for logical AND, | for logical OR, and ~ for logical NOT all return 1 for logical TRUE and 0 for logical FALSE To learn more about relational operators type help <=. 2.7 Flow Control 2.7.1 if statement

The if statement evaluates a logical expression and executes a group of statements when the expression is true. The optional elseif and else keywords provide for the execution of alternate groups of statements. An end keyword, which matches the if, terminates the last group of statements. The n cases are mutually exclusive, but if they weren't, the first true condition would be executed. The if statement can be used in conjunction with the nargin, nargout, and error functions to perform error checking of a function. Inside a function file, nargin and nargout are equal
Matlab Fundamentals Page 10

to the number of input and output arguments, respectively, that were used in function call. The command error(message) returns control to the keyboard and displays message. To find out more about for, while, break, if, and error type help lang in the MATLAB prompt SYNTAX: if expression statements end if expression1 statements elseif expression2 statements else statements end If the expression contain matrices such as A == B, it does not test if they are equal, it tests where they are equal; the result is another matrix of 0's and 1's showing element-byelement equality. In fact, if A and B are not the same size, then A == B is an error. To reduce the results of matrix comparisons to scalar conditions the following functions are useful: isequal, isempty, all, any 2.7.2 switch statement

The switch statement executes groups of statements based on the value of a variable or expression. The keywords case and otherwise delineate the groups. Only the first matching case is executed. There must always be an end to match the switch. Unlike the C language switch statement, MATLAB's switch does not fall through. If the first case statement is true, the other case statements do not execute. So, break statements are not required

SYNTAX: switch switch_expr case case_expr statement,...,statement case {case_expr1,case_expr2,case_expr3,...} statement,...,statement : otherwise statement,...,statement end

Matlab Fundamentals

Page 11

2.7.3

for loops

The for loop repeats statements a specific number of times SYNTAX: for variable = expression statements end 2.7.4 while loops

The while loop repeats a group of statements an indefinite number of times under control of a logical condition SYNTAX: while expression statements end 2.7.5 continue statement

continue passes control to the next iteration of the for or while loop in which it appears, skipping any remaining statements in the body of the loop. SYNTAX: continue 2.7.6 break statement

break terminates the execution of a for loop or while loop. In nested loops, break exits from the innermost loop only. SYNTAX: break 2.8 Script file A script file is an ASCII file that contains a series of MATLAB commands just as you would enter them in MATLAB command environment. Statement that begins with % is considered as comment and is ignored by MATLAB. The script file may be created outside the MATLAB environment with any text editor or word processor. Each script file should have a name that ends with .m The commands in the script file are executed in the MATLAB environment by simply entering the name of the script file without the extension .m

Matlab Fundamentals

Page 12

2.9 Creating Functions Function files are m-files that are very similar to script files. The first major difference is that the first line of a function file begins with the word function, followed by a statement identifying the name of the function and the input and output argument in the form

The second major difference between function files and script files is that the variables generated in function files are local to the function, whereas variables in script files are global. 2.10 Graphics in Matlab

MATLAB can create high-resolution, publication-quality 2-D, 3-D, linear, log, semilog, polar, bar chart and contour plots on plotters, dot-matrix printers, and laser printers. Some of the 2-D graph types are plot, loglog, semilogx, semilogy, polar, and bar. The command grid adds a grid to the graph, and the command title(text), xlabel(text), ylabel(text), and text(text) can be used for labeling and placing text on the graph. MATLAB provides automatic scaling. The command axis([xmin, xmax, ymin, ymax]) enforces manual scaling. Shown in table 1-6 are some of the useful commands in 2D graphics. Table 1-6. Elementary x-y graph and Anotation Fill Draw filled 2-D polygon loglog log-log scale plot plot linear plot semilogx semi-log scale plot semilogy semi-log scale plot stem Discrete sequence or "stem" plot subplot Create axes in tiled positions grid Grid lines gtext Mouse placement of text text Text annotation title Graph title xlabel x-axis label ylabel y-axis label
Matlab Fundamentals Page 13

III. Exercise will be posted on Monday (June 4, 2007). Please see updated file on Monday

Matlab Fundamentals

Page 14

Vous aimerez peut-être aussi