Modul matlab PDF

Title Modul matlab
Author Ivan Begovic
Course Data Communications and Networks
Institution New York University
Pages 19
File Size 291.1 KB
File Type PDF
Total Downloads 32
Total Views 124

Summary

Tutorial Matlab...


Description

ET3260in/ET2505-D1 Practical Stochastic Processes in MATLAB

2 November 2006 Session 1

Session 1 – Intr Introduction oduction to the use of MA MATL TL TLAB AB Part 1 MA MATLA TLA TLAB B 1. 2. 3. 4. 5. 6.

Introduct Introduction ion Matrices Matrix oper operations ations and fun functions ctions Visualization M-files Control state statements ments

Part 2 Modeling Networ Network kT Tra ra raffic ffic 1. Introdu Introduction ction 2. Theory 3. Packet tr transf ansf ansfer er time

Part 1 MA MATLA TLA TLAB B 1. Introdu Introduction ction MATLAB is a technical software environment based on matrix manipulations offering both numerical processing and visualization tools. MATLAB combines numerical analysis, matrixcomputation, signal and image processing and visualization tools with a simple user-friendly environment. Problems and solutions are expressed using statements, which resemble standard mathematical expressions without the need for developing software using traditional programming techniques such as C, Pascal or Java. The goal of the introduction to the use of MATLAB is offering the student basic MATLAB knowledge enough for a successful completion of the exercises of this course. A more extensive introduction to MATLAB can be found in various textbooks, such as “Getting started with MATLAB, The MATHWORKS, Inc., 1999”.

2. Matrices MATLAB operates on a single object, a matrix, possibly including complex elements. Scalars are treated as matrices, column vectors as matrices, and row vectors as matrices. In this section, we will describe in detail how to work with matrices, how to write/read variables and how to select sub-matrices. Generatin Generating g matrices To declare a (row) vector with, for example, elements 1, 3 and 4, we can type the following: >> a = [1 3 4] a= 134

Another way to declare vectors is to use an arbitrary increment between its elements, for example: >> b = [0:2:6]

1-1

ET3260in/ET2505-D1 Practical Stochastic Processes in MATLAB

2 November 2006 Session 1

b= 0246

or simply: >> b = 0:2:6 b= 0246

This results in an integer vector with an increment of 2 between successive elements. The default increment size (if not explicitly given) is 1. The transpose of a matrix or a vector is given by the operation ’, that is, >> a’ ans = 1 3 4

results in the transposed of the row vector, i.e. a column vector. Special attention should be given to the fact that the MATLAB operation ’ transposes and complex-conjugates matrices. For transposition only, use the command .’ . The last result of any operation that is not saved in a specific variable, is kept by MATLAB in the default variable ans (answer). If you want to further manipulate the result of an operation, assign the result to a (new) variable, for instance: >> b = a’ b= 1 3 4

Do not base further manipulations on the default variable ans. It is possible to generate a column vector by separating the different rows using the semicolon, i.e., >> [1; -3; 4] ans = 1 -3 4

Of course we can also define vectors with complex elements, using either i or j as the imaginary unit. For example: >> c = [2+i; -i] c= 2.0000 + 1.0000i 0 - 1.0000i

but also

1-2

ET3260in/ET2505-D1 Practical Stochastic Processes in MATLAB

2 November 2006 Session 1

>> c = [2-j j]’ c= 2.0000 + 1.0000i 0 - 1.0000i

A matrix is defined in the same way as a vector. This is done by defining either a row vector of columns, or a column consisting of rows, where the different rows are separated by a semicolon, e.g.: >> A = [[1 4 7]’ [2 5 8]’ [3 6 9]’] A= 123 456 789

or >> A = [1 2 3; 4 5 6; 7 8 9] A= 123 456 789

Note that MATLAB is case sensitive (aA) and that terminating the command line with a semicolon suppresses the display of its result. This feature will become essential when we want to display the final result of complex computations, not being interested in intermediate results. MATLAB includes many built-in functions for automatic matrix creation. Among these are: zeros (matrix with zeros), ones (matrix with ones), eye (identity matrix). Submatrices MATLAB allows the selection of specific parts of a vector. For instance, to view only the first three elements of the vector b, we can type: >> b(1:3) ans = 024

To view the first and third element, type: >> b([1 3]) ans = 04

If we wish to select all the elements starting at a given position up to and including the last element, we can use the variable end: >> b(2:end) ans = 246

Note that the first vector element in MATLAB is indexed 1, and not 0. Hence:

1-3

ET3260in/ET2505-D1 Practical Stochastic Processes in MATLAB

2 November 2006 Session 1

>> b(0) ??? Index exceeds matrix dimensions.

This is one of the most common error messages an inexperienced MATLAB user will encounter. Just like vectors, we can select matrix elements, for example the element (1,2) of matrix A: >> A(1,2) ans = 2

Notice that the elements in a matrix are denoted using round brackets ( ), and not with square brackets [ ]. The square brackets are used for entering values into a matrix. To extract the first two columns, type >> A(1:3,1:2) ans = 12 45 78

The same result can be achieved by typing: >> A(:,1:2) ans = 12 45 78

Here, the colon means “all elements”. To select the entire matrix, we therefore type: >> A(:,:) A= 123 456 789

Conversely, one can also insert a (sub-)matrix into another matrix (as opposed to the above extraction procedure). For instance: >> A(:,:) ans = 123 456 789 >> B(:,:) ans = -1 –2 -3 –4 >> A(1:2,1:2) = B ans = -1 -2 3 -3 -4 6 7 8 9

1-4

ET3260in/ET2505-D1 Practical Stochastic Processes in MATLAB

2 November 2006 Session 1

Variables We can get the list of all currently defined variables using the commands whoand whos: >> who Your variables are: A a ans b

c

>> whos Name Size Bytes Class A 3x3 72 double array a 1x3 24 double array ans 3x2 48 double array b 1x4 32 double array c 2x1 32 double array (complex) Grand total is 24 elements using 208 bytes

Alternatively, the variables in the Workspace can be inspected via the graphical user interface (see Workspace tab in the MATLAB interface). To view the dimension of a specific variable, use the size command, for example: >> size(b) ans = 14

It is often sufficient to know only the length of a vector. Use the command length: >> length(b) ans = 4

The clear command deletes a particular variable: >> clear c >> who Your variables are: A a ans b

When exiting a MATLAB session, all variables are destroyed. However, with the command save it is possible to save all declared variables to the file ‘matlab.mat’ before exiting the session. Later, when starting a new session, one can read these saved variables by typing load. Instead of saving to the file ‘matlab.mat’, another file name can be used as follows: >> save MyWorkspace

The entire workspace is now saved in the file ‘MyWorkspace.mat’. It is also possible to save only specific variables. For example, to save the matrix A to a file named ‘A_matrix.mat’, type: >> save A_matrix A

1-5

ET3260in/ET2505-D1 Practical Stochastic Processes in MATLAB

2 November 2006 Session 1

This file can be read later with the command: >> load A_matrix

3. Matrix oper operations ations and ffunctions unctions In this section, we explore different matrix manipulation techniques. Matrix oper operations ations As you might have noticed by now, MATLAB uses the standard linear algebra notation. Both linear and non-linear operations, like addition, subtraction, multiplying, and raising to a power (+,-,* and ^, respectively) can be achieved easily. Pay attention to the dimensions of the matrices and vectors when operating on more than one variable. See the following examples: >> A*a ??? Error using ==> * Inner matrix dimensions must agree. >> A*a’ ans = 19 43 67 >> b(2:4)*A ans = 60 72 84 >> a + b([1 2 4]) ans = 1 5 10

It is sometimes desirable to perform element-wise operations. This is done by placing a point before the mathematical symbol. For example, to raise each element of matrix A to the power of two, we type: >> A.ˆ2 ans = 1 4 9 16 25 36 49 64 81

This is not equivalent to >> Aˆ2 ans = 30 36 42 66 81 96 102 126 150

indicating the matrix product AA = A2. Matrix functions MATLAB has many built-in functions. Some (e.g. sin) work on scalars. When called with a matrix argument, those functions will work on each element individually:

1-6

ET3260in/ET2505-D1 Practical Stochastic Processes in MATLAB >> sin(b) ans = 0 0.9093 >> max(sin(b)) ans = 0.9093

-0.7568

2 November 2006 Session 1

-0.2794

When working with random variables and stochastic processes, we will often need to generate one or multiple outcomes or sample functions of random variables and processes, respectively. We use the function rand to generate a random number in the interval [0,1]. Every time you use randyour outcomes will (of course!) be different from the ones shown here, but must have the same properties: >> rand(1) ans = 0.0153 >> rand(1) ans = 0.7468 >> rand(1) ans = 0.4451

Other MATLAB functions work on vectors, but column-wise when called with matrix arguments. An example is the function max, which returns the largest element of a vector: >> rand(1,4) ans = 0.8913

0.7621

0.4565

0.0185

>> max(rand(1,4)) ans = 0.8214 >> Y = rand(3,4) Y= 0.4103 0.3529 0.8936 0.8132 0.0579 0.0099

0.1389 0.2028 0.1987

0.6038 0.2722 0.1988

>> max(Y) ans = 0.8936

0.8132

0.2028

0.6038 (selects max value per column)

>> max(Y') ans = 0.6038

0.8936

0.1988

(idem per row)

>> max(max(Y')) ans = 0.8936

1-7

ET3260in/ET2505-D1 Practical Stochastic Processes in MATLAB

2 November 2006 Session 1

The function max can also return the position of the maximum, for instance in the following example the variable q indicates in which row the maximum appears for each of the columns: >> [p,q] = max(Y) p= 0.8936 0.8132 q= 2 2

0.2028

0.6038

2

1

To use a mathematical function without knowing its name in MATLAB, we can use the command lookfor. Assume we want to generate random numbers. To find the corresponding MATLAB function, we can type: >> lookfor 'random numbers' RAND Uniformly distributed random numbers. RANDN Normally distributed random numbers. RANDOM Generates random numbers from a named distribution.

and we can choose the one that specifically serves our purposes. Note that if the string contains more than one word we must put quotes (‘.....’) around the string. To get help on a particular MATLAB function called ‘afunction’ type >> help afunction

Alternatively select "MATLAB Help" from the Help menu to access MATLAB’s extensive help functionalities. The following assignments should make you familiar with the above operations. Assignment 3.1. Generate a random vector X of length 50. Select all the elements at even positions, i.e. (2, 3, 6, 4, 7, 4, 1, 3)  (3, 4, 4, 3). Hint: use sub-matrix manipulations. Answer: a3_1 = rand(1,50) ; ans_a3_1 = a3_1([2:2:end])

Assignment 3.2. Insert into the result of the previous assignment a zero value between the elements, i.e. (2, 3, 6, 4)  (2, 0, 3, 0, 6, 0, 4). Hint: use sub-matrix manipulations.

Answer: ans3_2([1:2:50]) = ans_a3_1 Assignment 3.3. Replace the zero elements in the previous assignment by the average of the two neighboring elements, i.e. (2, 2.5, 3, 4.5, 6, 5, 4). Hint: use sub-matrix manipulations. Answer: ans_3_3 = ans3_2; ans_3_3([2:2:48]) = (ans3_2([1:2:47])+ans3_2([3:2:49]))/2

4. Con Control trol statements 1-8

ET3260in/ET2505-D1 Practical Stochastic Processes in MATLAB

2 November 2006 Session 1

In this section we study how to use the for, if and relational operators in MATLAB. These work slightly different as control statements in most computer languages. Rel Relational ational oper operations ations MATLAB’s relational operators are < less than > greater than = greater than or equal to == equal to ~= not equal to These relational operators are used element-wise, e.g. >> y = rand(1,4) y = 0.9501 0.2311 >> z = (y > 0.5) z = 1 0 1

0.6068

0.4860

0

Here the value zero has to be interpreted as the Boolean value “false”.

If If-statements -statements The general form of the if-statement is ifrelation

statements else

alternative statements end

The use of else is optional. The next example determines if a random number is negative (result = -1), positive (result = 1), or equal to zero (result = 0): >> number = randn number = 0.2342 >> if (number < 0), result = -1; elseif (number > 0), result = 1; else result = 0; end >> result result = 1

The brackets around the relations in the if-statements are not compulsory. In many cases, however, it does enhance code readability. Relations can be combined with the Boolean operator (&, |, and ~, logical and, or and not, respectively). For example, if we wish to determine whether a random number lies within the interval (0,½], we type:

1-9

ET3260in/ET2505-D1 Practical Stochastic Processes in MATLAB

2 November 2006 Session 1

>> number = randn number = 0.2734 >> if ((number > 0) & (number > result result = 1

Fo For-loop r-loop The for-loop has the following general form: for variable = vector

statements end

where the loop is iterated once for every value in vector. The following commands generate a row vector with elements 1, 2 en 3 using a for-loop: >> v = []; >> for n=1:3 v = [v n] end v= 1 v= 12 v= 123

Note that vector v is initialized by an empty matrix (v = []). Usually these operations can be performed easier by using sub-matrix manipulations (section 2). In this case v=1:3. The same methods can, of course, be used for matrix generation. For example: >> for m=1:2 for n=1:2 B(m,n) = (m+n)ˆ2; end end >> B B= 49 9 16

In MATLAB for-loops execute/run much slower than alternative implementations using matrix manipulations. Therefore, we prefer in this case: >> A = [1 2;1 2];

1-10

ET3260in/ET2505-D1 Practical Stochastic Processes in MATLAB

2 November 2006 Session 1

>> B = (A + A’).^2 B= 49 9 16

5. Visualization For the visualization of data we use graphical windows. The command figure opens such a window. >> figure

There are many ways to visualize data. The ones most used are plot for plotting twodimensional data. In this session we focus on plots of random data and their histograms. To plot a number of uniformly distributed outcomes, we type: >> n = 1:100; >> X = rand(1,100); >> plot(n,X);

Furthermore, we can adjust the plotting range and add a grid. >> axis([0 200 -0.1 1.1]); >> grid;

Several ways exist for plotting multiple functions at the same time with different colors and line types. We can do this using the command hold on: >> Y = X.^2; >> plot(X); >> axis([0 100 -0.1 1.1]); >> hold on >> plot(Y, ’r’);

In addition, you can generate two plots in different subplots in one figure (above or next to each other). To do this, use the command subplot. See the following example that creates a second figure: >> figure(2); >> subplot(2,1,1); >> plot(X); >> axis([0 100 -0.1 1.1]); >> subplot(2,1,2); >> plot(Y); >> axis([0 100 -0.1 1.1]);

Adding text to figures is simple: >> subplot(2,1,1); >> xlabel ('n'); >> ylabel ('x'); >> title ('Example plot of 2 subplots'); >> subplot(2,1,2);

1-11

ET3260in/ET2505-D1 Practical Stochastic Processes in MATLAB

2 November 2006 Session 1

>> xlabel ('n'); >> ylabel ('y = x*x');

Note that text in MATLAB is placed between single quotes (double quote is never used in MATLAB). If desired, the colors and line type of the subplots can be changed. Try the following commands: >> plot(X, 'bo'); >> plot(Y, 'r+');

For more visualization options of the command plot, see help plot. The close command closes figures, effectively deleting the graphical window. For instance to close the second figure: >> close figure(2)

or to close all figures: >> close all

Assignment 5.1. Generate 1000 outcomes of a Gaussian probability model in a single vector X, 1000 outcomes of an uniform probability model in the vector Y, and the sum of both series of outcomes, i.e. Z=X+Y. Plot these three vectors in a single figure in overlap with each other. Also plot these vectors in three subplots of one figure. Label and title both plots and use different colors for the data. Answer: x=randn(1,1000); >> y=rand(1,1000); >> z=x+y; plot(x, 'b'); >> hold on; >> plot(y, 'r'); >> hold on; >> plot(z, 'g'); subplot(3,1,1); >> plot(x); >> title('x values'); >> xlabel('x'); >> hold on; >> subplot(3,1,2); >> plot(y, 'r'); >> title('y values'); >> xlabel('y'); >> hold on; >> subplot(3,1,3); >> plot(z, 'g'); >> title('z values'); >> xlabel('z');

1-12

ET3260in/ET2505-D1 Practical Stochastic Processes in MATLAB

2 November 2006 Session 1

6. M-files MATLAB can execute statements from a text file. These files (called m-files) must have the file extension ‘.m’. There are two types of m-files: script files and function files. We strongly recommend that you solve ALL MATLAB sessions by first editing an m-file and then executing the m-file. We use the MATLAB text editor to create an m-file. Script files A script file contains a series of MATLAB statements. As such, a script file avoids the need to retype the same series of commands in the MATLAB command window. It is good MATLAB programming practice to always start a script file with the commands close all and clear all. All variables within that file are global and will conflict with variables having the same name in the current MATLAB session. As an example, let us assume that we wish to plot a given function. The script file will take the following form: % script file for plotting a function close all clear all % generate data according to the function xvalues = -10:0.1:10; data = normpdf(xvalues,-2,2.5); % open a figure and plot the function figure; plot(xvalues,data); xlabel(’x’); ylabel(’f(x)’);

Save the m-file as ‘myscript.m’, and execute the script by either typing the command ‘myscript’ in the command window, or by clicking on the run-button in the MATLAB editor.

Function files Function files enable the definition of new functions in MATLAB. Variables inside a function file are local by default. We demonstrate the use of a function file with a simple example, which generates a matrix of random integers. function y = rand_int(m,n,range); % rand_int Randomly generated integer matrix. % rand_int(m,n,range) returns an m-by-n such matrix whose % entries are between 0 and range. % generate random integer matrix

1-13

ET3260in/ET2505-D1 Practical Stochastic Processes in MATLAB

2 November 2006 Session 1

y = floor((range+1)*rand(m,n));

The first line declares the function rand_int, together with input and output arguments (m,n,range) and (y), respectively. Without this line, the file would be an ordinary script file. The parts of the file that follow the symbol “%” are considered comments. Use enough comments to explain the operation of your ...


Similar Free PDFs