Vous êtes sur la page 1sur 11

-1LAB MANUAL 1

MATLAB BASICS
Student Name: ___________________________ Roll No: ___________________________ Date: Grades: ______________________ ______________________

It is a programming environment that has gained tremendous popularity due to its ease of use. It is a matrix based system for scientific and engineering calculations. Its strength lies in the fact that complex numerical problems can be solved easily and efficiently. The name MATLAB is an abbreviation of MATrix LABoratry. This beginning chapter tends to introduce the basic working environment of MATLAB.

1. MATLAB BASICS
MATLAB displays a command window for interpreting commands. When MATLAB is invoked, the command window will display the prompt >>. MATLAB is then ready for entering data or executing commands. To quit MATLAB, type the command exit or quit. MATLAB has an excellent help facility. To see the list of MATLABs help facility, type help. The help command followed by a function name is used to obtain information on a specific MATLAB function. Another useful command to find detail of any command is doc. Its syntax is >> doc command_name 1.1 BASIC ARITHMATIC OPERATIONS MATLAB uses the symbols +,-,*,/,^ for addition, subtraction, multiplication, division and exponentiation of scalars (a scalar is a single number). The precedence and MATLAB forms of these operators are Symbol ^ * / \ + 1.2 VARIABLES Storage of data and variables is allocated automatically once the data and variables are used. When we type most commands to MATLAB, they return values. These values can be assigned to variables. e.g. --------------------------------------------------------------------------------------------------------------------------DSP LAB, Electrical Engineering Deptt. , UET Lahore.

Operation Exponentiation ab Multiplication ab Right Division a/b=a div b Left Division a\b=b diva Addition a+b Subtraction a-b

MATLAB Form a^b a*b a/b a\b a+b a-b

-2>> y =10 MATLAB will return y = 10 And will assign the number 10 to x. If a variable is not assigned, the answer of the expression will be stored in a default variable ans. So if it is typed, >> 10 MATLAB will assign the value 10 to variable ans. Sometimes, we dont want the result of a calculation to be displayed. A semicolon ; placed after the expression will suppress the display of output. e.g. >> y = 10; >> Now 10 is assigned to variable y and rather than displaying the result, it will just return another >> prompt. PRACTICE Evaluate -4^2 ________ and (-4)^2 ________. Why is there a difference between two values. 1+1:5 ____________________ and 1+[1:5] ____________________. Why is there a difference between two values? 4^2-12-8/4*2 ________________ If x = 20, evaluate y, y= 7(x1/3) + 4 x0.58 y= (1-1/x5)-1 27^ 1 / 3 + 32 ^ 3 _________________.

2.

VECTORS & MATRICES

The basic data object in MATLAB is a rectangular numerical matrix with real or complex elements. Scalars are thought of as a 1-by-1 matrix. Vectors are considered as matrices with a row or a column. Values are assigned to the elements of a matrix by using brackets. A space (or a comma) is a separator and takes to the next column while semicolon takes to the next line. Elements are indexed starting from 1. The first index is the row number and second index is the column number. --------------------------------------------------------------------------------------------------------------------------DSP LAB, Electrical Engineering Deptt. , UET Lahore.

-3A matrix

1 2 3 A= 4 5 6 7 8 9 can be entered in MATLAB as


>> A = [1 2 3; 4 5 6; 7 8 9]; A matrix A can also be entered across three input lines as >> A = [ 1 2 3 4 5 6 7 8 9]; In this case, the carriage returns replace the semicolons. In above example A (1,1) will return 1 and A (2,3) will return 6.A row vector B with four elements B = [ 6 9 12 15 18 ] can be entered as >> B = [6 9 12 15 18]; or >> B = [6,9,12,15,18]; PRACTICE >> a = [1 2 3; 4 5 6]; >> a = [a a]

% Type and write the output

>> a= [1 2 3; 4 5 6] >> a= [a;a]

% Type and write the output

>> a=[1 2;3 4 5]

% Type and write the output

3. MATRIX OPERATIONS
Matrices of the same dimension may be subtracted or added. Thus if E and F are entered in MATLAB as >> E = [7 2 3; 4 3 6; 8 1 5]; --------------------------------------------------------------------------------------------------------------------------DSP LAB, Electrical Engineering Deptt. , UET Lahore.

-4>> F = [1 4 2; 6 7 5; 1 9 1]; Then, G = E F and H = E + F can be calculated. Matrix multiplication is defined provided the inner dimensions of the two operands are the same. Thus, if X is an n-by-m matrix and Y is i-by-j matrix, X*Y is defined provided m is equal to i. If Z*I =V and Z is non-singular, the left division, Z\V is equivalent to MATLAB expression I =inv(Z)*V where inv is the MATLAB function for obtaining the inverse of a matrix. The right division denoted by V/Z is equivalent to the MATLAB expression I=V * inv(Z) The transpose of a matrix is found by using the operator. e.g. to find the transpose of a matrix G , we will write >> D=G There are MATLAB functions that can be used to produce special matrices. Some useful functions of matrices are as follows, ones(n,m) eye(n) zeros(n,m) diag(A) Produces n-by-m matrix with all the elements being unity gives n-by-n identity matrix Produces n-by-m matrix of zeros Produce a vector consisting of diagonal of a square matrix A

4. ACCESSING COLUMNS AND ROWS


Let us suppose that we have a matrix 1 2 b= 3 4 5 6 Now, what if we want to add another row into b? we can simply write b (4,:)=[7 8]. Notice the colon in the place of a column specifier. It is a trickier way to specify the whole range. We can have used b (4,1:2) = [7 8] for the same purpose. So the new matrix b obtained will be >> d (4,:) = [7 8] d = 1 2 3 4 5 6 7 8 If we want to select column 1 only? The following code will do this. >> b (:,1) ans = --------------------------------------------------------------------------------------------------------------------------DSP LAB, Electrical Engineering Deptt. , UET Lahore.

-51 3 5 7 PRACTICE If we want to select the 2nd row only, what should we write, >> % Type the code and show the output

5. NUMBER RANGES
The colon symbol (:) is one of the most important operators in MATLAB. It can be used (1) to create vectors and matrices, (2) to specify sub-matrices and vectors, and (3) to perform iterations. The statement >> u = 1 : 6 will generate a row vector containing the numbers from 1 to 6 with unit increment. MATLAB produces the result u = 1 2 3 4 5 6 Non-unity, positive or negative increments, may be specified. For example, the statement >>h = 3:-0.5:1 h = 3.0000 2.5000 2.0000 1.5000 1.0000 PRACTICE >> t = [(0:2:10);(5:-0.2:4)] % Write the result

6. ARRAY OPERATIONS
Array operations refer to element-by-element arithmetic operations. Preceding the linear algebraic matrix operations, * / \ , by a period (.) indicates an array or element-by- element operation. Thus, the operators .* , .\ , ./, .^ , represent element-by-element multiplication, left division, right division, and raising to the power, respectively. For addition and subtraction, the array and matrix operations are the same. Thus, + and .+ can be regarded as an array or matrix addition. If A and B are matrices of the same dimensions, then A.*B denotes an array whose elements are products of the corresponding elements of A and B. Thus, if --------------------------------------------------------------------------------------------------------------------------DSP LAB, Electrical Engineering Deptt. , UET Lahore.

-6>> A = [2 7 6; 8 9 10]; >> B = [6 4 3; 2 3 4]; >> C = A.*B C = 12 16 28 27 18 40

An array operation for left and right division also involves element-by-element operation. The expressions A./B and A.\B give the quotient of element by- element division of matrices A1 and B1. Thus, >>D = A./B D = 0.3333 1.7500 2.0000 4.0000 3.0000 2.5000 and the statement >> E1 = A.\B E1 = 3.0000 0.5714 0.5000 0.2500 0.3333 0.4000 The array operation of raising to the power is denoted by .^ The general statement will be of the form: >> q = r.^s PRACTICE >> r = [7 3 5]; >> s = [2 4 3]; >> q = r.^s

% Write the matrix q

7. CONDITIONAL & LOOPING COMMANDS


The format of the for, while and if commands is similar to the format of the most other computer languages. For example, the statement for i= 1:n x(i) = i^2; end will produce n dimension vector x = [1, 4, 9, , n2] --------------------------------------------------------------------------------------------------------------------------DSP LAB, Electrical Engineering Deptt. , UET Lahore.

-7The general form for a while loop is while relation <Statements> end The statements will be repeatedly executed as long as the relation is true. e.g. for a given number a, the following will compute the smallest non-negative integer n such that 2n > =a; n = 0; while 2^n < a n = n + 1; end The general form of an if statement is illustrated by if n < 0 x (n) = 0; elseif rem (n,2) = = 0 x (n) = 2; else x (n) =1; end

8. POLYNOMIAL OPERATIONS
Vectors can also be used to represent polynomials. If we want to represent an Nth order polynomial, we can use a length N+1 vector where the elements are the coefficients of the polynomial arranged in descending order of exponent. So, to define y= x2 5x + 6, we should type, >> y = [1 -5 6] ROOT COMMAND The MATLAB roots function will calculate the roots of a polynomial. If we use the y from above, >> roots (y) ans = 2 MATLAB also has the poly function, which takes a vector and returns the polynomial whose roots are the elements of that

9. GRAPHICAL DISPLAY OF RESULTS


There are several commands for graphically displaying results. plot command is used for continuous time plots and to graphically display the results. --------------------------------------------------------------------------------------------------------------------------DSP LAB, Electrical Engineering Deptt. , UET Lahore.

-8 If x and y are two real vectors of same length, then plot (x,y) displays the graph of y as a function of x. If x and y are two real matrices of the same size, then plot (x,y) displays the first column of y as a function of first column of x, the second column of y as a function of second column of x and so on until no column is left. If x is a real vector of length N and y is a real matrix of size (N x K), then plot (x,y) displays K graphs corresponding to the K columns of y as a function of x. If x is a complex vector, then plot (x) displays the graph of imaginary part of x as a function of real part of x.

If a command subplot (3,2,4) or subplot (324) is added before the plot command, the graph is divided in six sub windows of three lines with two columns each and display is done in subwindow number 4. To plot a discrete sequence stem command is used. e.g. stem (x,y) where x and y are two arrays of same sizes. Three dimensional mesh surface plots are drawn with the function mesh. The command mesh (z) creates a three dimensional plot of the elements of the matrix z. The mesh surface is defined by the z coordinates of points above a rectangular grid in the x-y plane. Some other useful commands of use are % length clear clear X clc clg who diary Comments. Everything appearing after % command is not executed. Length of a matrix Clears the variables or functions from workspace Clears the variable X or a function X from workspace. Clears the command window during a work session Clears graphic window Lists the variables in the current workspace. Saves a session in a disk, possibly for printing at a later date

10. 10. M FILES CREATION


MATLAB is also capable of processing a sequence of commands that are stored in files with extension m. MATLAB files with extension m are called m-files. To list m-files in the current directory on your disk, you can use the MATLAB command what. The MATLAB command, type, can be used to show the contents of a specified file. M-files can either be script files function files.

Both script and function files contain a sequence of commands. However, function files take arguments and return values. 10.1 10.1 Script Files --------------------------------------------------------------------------------------------------------------------------DSP LAB, Electrical Engineering Deptt. , UET Lahore.

-9Script files are especially useful for analysis and design problems that require long sequences of MATLAB commands. With script file written using a text editor or word processor, the file can be invoked by just entering the name of the m-file, without the extension. Statements in a script file operate globally on the workspace data. It means the variables that are in a script are same as are in the workspace. If there is a variable a =5 in the work space and if some script is run that assigns a =10, now the value of the variable a in the workspace is also changed to 10. Normally, when m-files are executing, the commands are not displayed on screen. The MATLAB echo command can be used to view m-files while they are executing. A script file should not have a word function in the first line. 10.2 10.2 Function Files Function files are m-files that are used to create new MATLAB functions. Variables defined and manipulated inside a function file are local to the function, and they do not operate globally on the workspace. However, arguments may be passed into and out of a function file. The first line of the file specifies the function name along with the names and numbers of input arguments and output values. The general form of a function file is function variable(s) = function_name (arguments) % help text in the usage of the function % . . end Example: function req = equiv_sr(r) % equiv_sr is a function program for obtaining the equivalent % resistance of series connected resistors % usage: req = equiv_sr(r) % r is an input vector of length n % req is an output, the equivalent resistance (scalar) % n = length(r); % number of resistors req = sum (r); % sum up all resistors end

EXERCISES
1. The classic quadratic formula says that the two roots of the
quadratic equation ax + bx + c = 0 x1, x2 = -b + [( b2 4 ac)] / (2a) Use this formula in MATLAB to compute both roots for a = 1 , b = -100000000 , c = 1 Compare your results with >> roots([a,b,c])
2

--------------------------------------------------------------------------------------------------------------------------DSP LAB, Electrical Engineering Deptt. , UET Lahore.

- 10 -

2. Given the array A = [2 4 1 ; 6 7 2 ; 3 5 9], provide the


commands needed to a. b. c. d. e. assign the first row of A to a vector called x1 assign the last 2 rows of A to an array called y compute the sum over the columns of A compute the sum over the rows of A compute the standard error of the mean of each column of A

(NB. the standard error of the mean is defined as the standard deviation divided by the square root of the number of elements used to compute the mean.)

3. Given the array A = [2 7 9 7; 3 1 5 6; 8 1 2 5],provide the


command that will a. b. c. d. e. assign the even-numbered columns of A to an array called B assign the odd-numbered rows to an array called C convert A into a 4-by-3 array compute the reciprocal of each element of A compute the square-root of each element of A

4. Given the array A = [2 7 9 7 ; 3 1 5 6 ; 8 1 2 5], explain


the results of the following commands: a. b. c. d. e. f. g. h. A(:,[1 4]) A([2 3],[3 1]) reshape(A,2,6) A(:) fliplr(A) A(1:3,:) [A ; A(1:2,:)] [ [ A ; sum(A) ] [ sum(A,2) ; sum(A(:)) ] ]

5. Let x = [3 2 6 8]' and y = [4 1 3 5]' (NB. x and y should be


column vectors). a. Add the sum of the elements in x to y b. Raise each element of x to the power specified by the corresponding element in y. c. ivide each element of y by the corresponding element in x d. Multiply each element in x by the corresponding element in y, calling the result "z". e. Add up the elements in z and assign the result to a variable called "w". f. Compute x'*y - w and interpret the result --------------------------------------------------------------------------------------------------------------------------DSP LAB, Electrical Engineering Deptt. , UET Lahore.

- 11 -

6. Create a vector x with the elements,


xn = (-1)n+1/(2n-1) Add up the elements of the version of this vector that has 100 elements. 7. Plot the expression (determined in modelling the growth of the US population) P(t) = 197,273,000/(1 + e-0.0313(t
- 1913.25)

) What

where t is the date, in years AD, using t = 1790 to 2000. population is predicted in the year 2020?

8. Evaluate the given MATLAB code fragments for each of the


cases indicated. Use MATLAB to check your answers. if T < 30 h = elseif h = else h = end a. T = 50 b. T = 15 c. T = 0 2*T + 1 T < 10 T - 2 0 h = ? h = ? h = ?

Create an M-by-N array of random numbers (use rand). Move through the array, element by element, and set any value that is less than 0.2 to 0 and any value that is greater than (or equal to) 0.2 to 1.

9.

10. Take A = [1 3;5 7;8 9] and B = [2 4;6 8; 9 10] and verify


all four points for graphical representation of calculations mentioned in section 9 of this manual. (Take any vector of suitable size where needed) 11. Write a function that takes a matrix as input and then after taking its transpose flips its columns about vertical axis. Use this function to in matlab workspace for two matrices A=[1 2 3;4 5 6;7 8 9] and B= [1 3 5; 2 5 7; 3 9 1] and then add the rows of the resulting two matrices.

--------------------------------------------------------------------------------------------------------------------------DSP LAB, Electrical Engineering Deptt. , UET Lahore.

Vous aimerez peut-être aussi