• Tidak ada hasil yang ditemukan

Introduction to MATLAB for Network Traffic Modeling

N/A
N/A
Yova Aprilia

Academic year: 2024

Membagikan "Introduction to MATLAB for Network Traffic Modeling"

Copied!
18
0
0

Teks penuh

(1)

Session 1 – Introduction to the use of MATLAB Part 1 MATLAB

1. Introduction 2. Matrices

3. Matrix operations and functions 4. Visualization

5. M-files

6. Control statements

Part 2 Modeling Network Traffic 1. Introduction

2. Theory

3. Packet transfer time

Part 1 MATLAB 1. Introduction

MATLAB is a technical software environment based on matrix manipulations offering both numerical processing and visualization tools. MATLAB combines numerical analysis, matrix- computation, 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.

Generating matrices

To declare a (row) vector with, for example, elements 1, 3 and 4, we can type the following:

>> a = [1 3 4]

a = 1 3 4

Another way to declare vectors is to use an arbitrary increment between its elements, for example:

>> b = [0:2:6]

b =

(2)

0 2 4 6 or simply:

>> b = 0:2:6 b = 0 2 4 6

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

34

Do not base further manipulations on the default variableans.

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

>> c = [2-j j]’

c = 2.0000 + 1.0000i

(3)

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 = 1 2 3 4 5 6 7 8 9 or

>> A = [1 2 3; 4 5 6; 7 8 9]

A = 1 2 3 4 5 6 7 8 9

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 vectorb, we can type:

>> b(1:3) ans =

0 2 4

To view the first and third element, type:

>> b([1 3]) ans =

0 4

If we wish to select all the elements starting at a given position up to and including the last element, we can use the variableend:

>> b(2:end) ans =

2 4 6

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

>> b(0)

??? Index exceeds matrix dimensions.

(4)

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 matrixA:

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

1 24 5 7 8

The same result can be achieved by typing:

>> A(:,1:2) ans =

1 24 5 7 8

Here, the colon means “all elements”. To select the entire matrix, we therefore type:

>> A(:,:) A = 1 2 3

4 5 6 7 8 9

Conversely, one can also insert a (sub-)matrix into another matrix (as opposed to the above extraction procedure). For instance:

>> A(:,:) ans =

1 2 3 4 5 6 7 8 9

>> B(:,:) ans =

-1 –2 -3 –4

>> A(1:2,1:2) = B ans =

-1 -2 3 -3 -4 6 7 8 9 Variables

We can get the list of all currently defined variables using the commandswhoandwhos:

>> who

Your variables are:

(5)

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 thesizecommand, for example:

>> size(b) ans =

1 4

It is often sufficient to know only the length of a vector. Use the commandlength:

>> length(b) ans =

4

Theclear 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 saveit 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

This file can be read later with the command:

>> load A_matrix

3. Matrix operations and functions

In this section, we explore different matrix manipulation techniques.

(6)

Matrix operations

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 productAA = 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:

>> sin(b) ans =

0 0.9093 -0.7568 -0.2794

>> max(sin(b)) ans =

0.9093

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 functionrand to generate a random number in the interval [0,1].

(7)

Every time you userand your 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 functionmax, 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.1389 0.6038 0.8936 0.8132 0.2028 0.2722 0.0579 0.0099 0.1987 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

The function max can also return the position of the maximum, for instance in the following example the variableq indicates in which row the maximum appears for each of the columns:

>> [p,q] = max(Y)

p = 0.8936 0.8132 0.2028 0.6038

q = 2 2 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'

(8)

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:

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:

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:

4. Control statements

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.

Relational operations

MATLAB’s relational operators are

< less than

> greater than

<= less than or equal to

>= greater than or equal to

== equal to

~= not equal to

These relational operators are used element-wise, e.g.

(9)

>> y = rand(1,4)

y = 0.9501 0.2311 0.6068 0.4860

>> z = (y > 0.5)

z = 1 0 1 0

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

If-statements

The general form of theif-statement is ifrelation

statements

elsealternative 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;

elseresult = 0;

>> resultend 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:

>> number = randn number =

0.2734

>> if ((number > 0) & (number <= 0.5)), result = 1;

elseresult = 0;

>> result =end result =

1 For-loop

Thefor-loop has the following general form:

(10)

for variable =vector statements

end

where the loop is iterated once for every value invector.

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]

v =end v = 1 v = 1 2

1 2 3

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 casev=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;

endend

>> B B = 4 9

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];

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

9 16

5. Visualization

For the visualization of data we use graphical windows. The command figureopens such a window.

>> figure

There are many ways to visualize data. The ones most used are plot for plotting two- dimensional data. In this session we focus on plots of random data and their histograms.

To plot a number of uniformly distributed outcomes, we type:

(11)

>> 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 commandhold 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 commandsubplot.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);

>> 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 commandplot, seehelp plot.

The closecommand closes figures, effectively deleting the graphical window. For instance to close the second figure:

>>close figure(2)

or to close all figures:

>>close all

(12)

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:

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 ofm-files: script files and function files.

We strongly recommend that you solve ALL MATLAB sessions by first editing anm-file and then executing them-file. We use the MATLAB text editor to create anm-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

(13)

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 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 yourm-fileand the way the file is to be used.

Save the file as‘rand_int.m’, and use the function as follows:

>> z = rand_int(3,2,5)

z = 2 5

4 5

4 2

The above function outputs a single variable. It is also possible to output more than one variable. This is done by changing the function definition to, for instance:

function [y,a] = rand_int(m,n,range);

As a simple example, we choose to set the variable a equal to the product of m and n. The resulting code is

function [y,a] = rand_int(m,n,range);

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

a = m*n;

This function is now used as follows:

>> [z,b] = rand_int(3,2,5)

z = 2 5

4 5

4 2

b = 6

(14)

Assignment 6.1 Write an m-file script called ‘bpm.m’ to generate 1000 outcomes of a binomial probability model with n=6 and p=0.4. The outcomes are put into the variable xbinomial. Hints: Usebinornd.

Answer:

Assignment 6.2 Extend the script file in Assignment 6.1 to estimate the probability P[outcome=3] (using the relative frequency). Hint: Usefind,length

Answer:

The estimation of relative frequencies (as estimators of probabilities) is usually done by making use of the histogram of a given set of outcomes. In MATLAB the command hist calculates the histogram of a vector. A histogram determines the number of outcomes that lie in a particular interval, called the bins of the histogram. The length of the intervals is called the bin-width or bin-size. Let us use the script of Assignment 6.2 to calculate and display the histogram of the outcomes with bin-size 0.4.

>> bpm

>> xhst = hist(xbinomial,-1.0:0.4:7.0);

>> figure;

>> bar(-1.0:0.4:7.0,xhst);

Note that the argument-1.0:0.4:7.0 defines the centers of the bins.

Assignment 6.3 Use the histogram to estimate the probabilities of all outcomes of the binomial probability model withn=6 andp=0.4. Explain the result.

Answer:

Assignment 6.4Write a function file ‘EstimateProb.m’that estimates the probabilities of randomly distributed numbers by computing the relative frequency of the individual bins. The syntax of the functionEstimateProbmust be:

[PX, X] = EstimateProb(Y,first_bin_center,binsize,last_bin_center);

When called, the input variable Y contains a series of outcomes. The arguments first_bin_center,binsize,last_bin_center define the events (intervals, bins) for which the relative frequency of occurrence is calculated. The output variables X and PX return the bin centers of the histogram and the associated relative frequencies, respectively.

Note: This function will often be used in subsequent MATLAB sessions.

(15)

Answer:

Assignment 6.5 Estimate the probabilities of the data generated under Assignment 6.1 by using the following function calls:

>> [PX, X] = EstimateProb(xbinomial,0,1,6);

>> figure;

>> bar(X,PX);

and

>> [PX, X] = EstimateProb(xbinomial,-5,0.5,12);

>> figure;

>> bar(X,PX);

Assignment 6.6Write anm-file script called‘gauss.m’ to generate 1000 outcomes of a Gaussian probability model (using normrnd) with =6 and =2.5. Note that in this case the outcomes are continuous in nature. Estimate the probabilities of occurrence of the events defined by self-chosen bins using the functionEstimateProb.

Answer:

Assignment 6.7 The parameters  and  of the Gaussian probability model represent the expected value and standard deviation, respectively. Estimate these parameters from the data of the previous assignment using mean and var. Do these estimates correspond with theandvalues used to generate the data?

Answer:

Assignment 6.8 (Tambahan)Silahkan diplot diagram batang (bar) dari luaran hasil fungsi EstimateProb pada Assignment 6. Kemudian silahkan anda plot pendekatan kurva PDF distribusi Gaussian (hint: lihat command normpdf) di atas diagram batang tersebut. Rentang nilai PDF distribusi Gaussian tentunya disesuaikan dengan rentang nilai pada sumbu horizontal (bins) hasil keluaran fungsi EstimateProb. Komentari apakah diagram batang dari luaran hasil fungsi EstimateProb cocok untuk didekati dengan Kurva PDF Gaussian? Berikan analisis selengkapnya.

Answer:

(16)

Part 2 Modeling Network Traffic

1. Introduction

Networks that stream voice or music across the Internet use packets to transfer the data streams. The transfer time of the individual packets varies due to switches, buffers and routers in the network. These variations change with the actual traffic load of the network.

As an illustrative example, the figure below shows the measured transfer times of data packets over the Sprint IP backbone network1 as a function of time. Indeed, these transfer times, sometimes called transfer delay, vary strongly depending on the network traffic load.

In order to maintain a required Network Service Level, such as a maximal transfer delay, all kinds of network dimensioning and management issues need to be continuously addressed.

2. Theory

Goal of this exercise is to understand: continuous and discrete random variables, estimates of the PDF and the PMF, expected value, variance.

3. Packet transfer time

The approach to network management is based on modeling of the packet transfer time as a random variable. We consider a simple network, for which we can measure the packet transfer time from the actual time of sending and actual time of arrival of that data packet at the receiving end. For this simple network a data set of packet number and packet arrival time is given in which the first packet is sent at t=0 and a next packet is sent every 10 ms.

The data set‘arrivaltimes.mat’ can be found on Blackboard in the folder containing this exercise.

a. Plot the data set in terms of packet number versus packet transfer time; paste the plot into the text.

Answer:

1 D. Papagiannaki, S. Moon, C. Fraleigh, P. Thiran, F. Tobagi, and C. Diot, “Analysis of Measured Single-Hop Delay from an Operational Backbone Network”,Proceedings of IEEE Infocom, June 2002

(17)

b. We consider the individual transfer times as outcomes of a random variable X. Model X as a uniform random variable. Use Appendix A of the text book to estimate the parameters of this PDF. Visualize the PDF in overlay with the relative frequencies of the transfer times. (Hint:mean,var,unifpdf)

Answer:

c. Model X as a Gaussian/normal random variable. Use Appendix A of the text book to estimate the parameters of this PDF. Visualize the PDF in overlay with the relative frequencies of the transfer times. (Hint:mean,var,normpdf)

Answer:

d. Compare the models from b. and c. Which of the two models do you prefer?

Answer:

e. Formulate at least one drawback of the PDF-model you selected in part d. Which solution(s) could be used to cope with the formulated drawback(s)? Discuss your results with the instructor.

Answer:

f. Let us now assume that the traffic load on the network increases. Logically, this may result in longer delays. How would you model this increased traffic load (by using your preferred model from assignment d.)? On the basis of your new

“increased traffic load” model, generate a transfer time data set of 2000 packets that represents the increased traffic load on the network. Visualize the PDF and your dataset as in assignment b. (Hint:rand, randn)

Answer:

(18)

g. In practical situations, like streaming music, packets are eliminated from the network when they travel around on the network for a too long period of time.

The receiving end observes this elimination as packet loss. Motivate and calculate the probabilities of packet loss for two self-chosen limits of the transfer time for your PDF as defined in assignment f. Also estimate these probabilities of packet loss from the data. Check whether the estimated probabilities correspond with the calculated probabilities.

Answer:

Referensi

Dokumen terkait