Sunteți pe pagina 1din 14

Random numbers Matlab has two functions for generating random numbers, rand, which generates random numbers

with the uniform distribution, and randn which generates random numbers according to the normal or "Gaussian" distribution. If you look up the description for rand and randn in Matlab's help, it mentions "pseudorandom" numbers. You will hopefully understand what the pseudo does at the end of this topic. A note of warning; this description is based on Matlab R 2008b. Since I started using Matlab for teaching the predecessor of this control course (with Matlab R 2005a), the interface and workings of the random number generator changed twice. This is a (often cursed) feature of Matlab, it seems to change right under your nose. If you have a non-trivial collection of Matlab scripts, count on updating these every two years or so. In Matlab you can select different algorithms for these generators, and all algorithms produce different series of random numbers. In these lectures I stick to the default for R2008b, which is the Ziggurat algorithm. Knowing Matlab, I expect this to change in the future! In some of the questions you need some random data for you to work on. Then, after you did your work, you are asked to enter the results in a field on this website, and the website program checks whether your calculations were correct. Of course, if the random generators would produce truly random (thus unpredictable) numbers, the answer cannot be checked. The reason that this works is that Matlab's random number generators do NOT generate random numbers, but instead generate pseudo-random numbers. Let's see whether you understand the implications here, and instead of me writing and you reading, you get to do some thinking and clicking, with the following question. Lecture 2: Matlab basics - random numbers - question 1 Mark Matrix creates a Matlab program to simulate the hub operation of an airport. This program uses the random number generator for generating random aircraft turnaround times, flight times and passenger walking times, and with his simulation he calculates the NOC rate (proportion of passengers who do not make it to the connecting flight). His program uses the standard random number generators in Matlab, and he does not do anything in particular to initialise them. On Saturday, he fires up his computer, fires up Matlab and runs his program 10 times while working on his report. After that he shuts down the computer. On Sunday, he switches on the computer again, fires up Matlab, runs the simulation another 6 times, assembles all data from the 16 runs, and writes the results and conclusion sections of his report, so he can hand that in on Monday. What happened? Your answer All simulations produced different results, pseudo-random numbers are random after all, except that they are created by a program. All simulations produced the same result, because the random generator generates pseudorandom numbers, and each time you use the generator it produces the same numbers. It was a good thing that he was typing his report at the same time that he ran his simulations, this resulted in the random numbers being truly random -- due to the irregularities in typing rythm, and Mark's results therefore are valid.

The 6 simulation runs Mark created on Sunday are an exact copy of the first 6 simulations on Saturday, invalidating his results.
Answ er

Your answer was correct! Additional feedback Nice work. Yes, The 6 simulation runs Mark created on Sunday are an exact copy of the first 6 simulations on Saturday, invalidating his results. Each time you start up Matlab, the same random numbers come out of its lottery. Just to warn you in advance, the most common mistakes I see in this exercise are:

Not properly reading the assignment, and using the wrong random number distribution, uniform where you need Gaussian, for example. Forgetting to reset the seed after you make a mistake: RandStream.getDefaultStream.reset(10); a = rand(5, 10); % Oh, no, I needed a 10 by 5 matrix a = rand(10, 5); % by this time, fresh random numbers come out

Lecture 2: Matlab basics - random numbers - question 2 Random numbers Matlab has three main functions for generating random numbers, rand, which generates random numbers with the uniform distribution, randn which generates random numbers according to the normal or "Gaussian" distribution and randi which generates random integer numbers. In Matlab you can select several different algorithms for these generators, all question assume you used the default one! As I told you Matlab messes around quite a bit with its random generator code, and it often changes. I am generating this database with the 2010b code, and I hope it produces the same results as your version! The 2008b and 2010b versions I tested use Ziggurat, let's hope Matlab keeps its current default random number generator for a while longer. My question is, what will the following command do in Matlab: RandStream.getDefaultStream.State Use the help function, and experiment with the random generator, to find out what the correct answer is. Your answer It gives the current state of the random generator. This state is not random, but determined by the seed and the number of random numbers pulled out of the generator.

It sets the initial state for the random generator. It will start the random generator with a new random numbers, so the random number generator output will by truly random. It gives the current state of the random generator. This state is basically useless, since it is random. It returns a special number called the "seed" of the random number generator. This is a number that you gave the random generator at its creation, and will be 0 in the case that you did not initialize it.
Answ er

Your answer was correct! Additional feedback Nice work. As the help file explains, RandStream.getDefaultStream.State returns the current state of the random generator. You can store this state in a variable, and use it to "rewind" the stream of random numbers, and exactly recreate the pseudo-random numbers you got before. For some reason, you cannot work directly with the default stream, but you need to copy it first % save the state savedstate = RandStream.getDefaultStream.State; % ask for some random numbers rand() rand(3,1) % reset the stream % you would think the following would work, but it does not, at least % on the Matlab versions I tried recently: % RandStream.getDefaultStream.State = savedstate; % % I think this is due to the imperfect implementation of classes in % Matlab; if you use two dots on the left-hand side of the assignment % operator =, (here .getDefaultStream and .State) Matlab % gets confused. Most Object Oriented languages that use dots to % access "class members" (Java, C++, Python) don't have this problem, % but Matlab does. % use the set function! set(RandStream.getDefaultStream, 'State', savedstate) % and the same random numbers come out rand() rand(3,1) When verifying Matlab programs that use random numbers, it is sometimes convenient to have a pre-defined set of random numbers come out of the random generator. You may do that by "seeding" the random number generator, taking a single number that defines the resulting behavior of your generator. It is also a nice method to let students play with random data and be able to check the outcome!

% set a seed of 5 RandStream.getDefaultStream.reset(5) % see what comes out rand(2,2) % do this again, and you get the same results RandStream.getDefaultStream.reset(5) rand(2,2) From this it should be clear to you that the random generator does not really generate random numbers, it generates pseudo-random numbers, and each time you start up Matlab, the same results come out of its lottery. P.s. The resetting described in the help for Matlab's rand also works. However, I like this method less, because you are manipulating defaultStream, which looks like a copy, but is actually a "handle", which means that it is just a different name for the default stream. Note that in Matlab 2011 versions and onwards, you should not call getDefaultStream butgetGlobalStream. defaultStream = RandStream.getDefaultStream; savedState = defaultStream.State; u1 = rand(1,5) defaultStream.State = savedState; u2 = rand(1,5) % contains exactly the same values as u1 Lecture 2: Matlab basics - variables - question 1 Summing a column Initialise the random number generator with a seed of 8. Then generate a random number matrix with 7 columns and 15 rows, using the uniform distribution. Add the numbers in the 6th column together, and enter the result in the field below. Note: In Matlab, use the default random generator (to be selected with 'RandStream.getDefaultStream'). There were 2 hints, of which you needed 67

Hint "Help on using the random number generator" (3 points, not used) Check the help function for rand on how to set the random number seed. Check the help function for sum to see how you can calculate the sum of all rows in a matrix.

Hint "Specific help on using the random number generator" (5 points, not used) With Matlab, use % set a seed RandStream.getDefaultStream.reset(5) To initialise the random number generator. Note that the function rand only produces uniform numbers.

The call a = rand(15, 7) generates a random number matrix of 15 rows and 7 columns, and selecting the 6th column from a can be done with a(:, 6). Your answer Give the sum of the numbers in the 6th column of the matrix.
Answ er
9.3095

Your answer was correct! Additional feedback Very good, a perfect score. Rather than starting to program, use the function sum: In Matlab: RandStream.getDefaultStream.reset(8) a = rand(15, 7) sum(a(:,6)) Lecture 2: Matlab basics - variables - question 2 Create an identity matrix with size 24. Then calculate the trace of this identity matrix. There was one hint which you did not need

Hint "A random hint" (3 points, not used) Check the help for functions eye and trace

Your answer Give the trace of the created identity matrix.


Answ er
24

Your answer was correct! Additional feedback Nice to see that you are mastering this. If you know what trace does, this question is actually a bit silly. size = fill_in_matrix_size trace(eye(size, size)) Lecture 2: Matlab basics - variables - question 3 Substituting a row Initialise the random number generator with a seed of 2. Then create a random number matrix with 6 columns and 6 rows, using the uniform distribution. Now replace the 5th row

of the created matrix with the row vector [2 3 4 5 6 7]. Calculate the sum of all elements in the matrix, and enter the result in the field below. Note: In Matlab, use the default random generator. There was one hint which you did not need

Hint "Selecting and replacing part of a matrix" (6 points, not used) If you have a matrix a, then a(5,:)selects the fifth row. You can also use this selection to replace the variables in that row, for example to put new random variables in:

a(5,:) = rand(a(5, :)) Your answer Give the sum of all elements in the matrix
Answ er
37.9888

Your answer was correct! Additional feedback Fine job! The answer combines generating a sequence (2:7), you know this will become a row vector, and using this sequence to replace the 5th row of the result: In Matlab: RandStream.getDefaultStream.reset(2) a = rand(6, 6) a(5,:) = 2:7 sum(sum(a)) Lecture 2: Matlab basics - variables - question 4 Appending rows Initialise the random number generator with a seed of 5. Select the normal (Gaussian!) distribution, and create a random number matrix of 5 rows by 5 columns. Round off the elements in the matrix to the nearest integer value. Extend the matrix, by adding a row vector of five elements as last row of the matrix, and a column vector of 6 elements as last column, making this a 6 by 6 matrix. The row vector and column vectors are: rowvector = -2:1:2 columnvector = (0:5)' The prime 'creates the transpose of a matrix.

Calculate the number of nonzero elements. Note: In Matlab, use the default random generator (to be selected with RandStream.getDefaultStream). There were 2 hints, of which you needed 10

Hint "Juggling with matrices" (2 points, not used) Instead of using single elements in creating a matrix, you can also compose a matrix out of existing matrices and vectors, as an example, with A being a matrix with 6 columns, and bbeing a row vector with 5 elements (so 5 columns) you can do: C = [A ; b 0]

Hint "Which help pages to look at" (1 points, not used) Check the help for randn and round and nnz.

Your answer Give the number of nonzero elements in the matrix


Answ er
22

Your answer was correct! Additional feedback Fine job! You can combine the matrices in a single step as follows: b = [[a ; rowvector] columnvector] The complete solution is: rng(5) % assuming your matlab is >= 2011a m = [ [round(rand(5,5)); -2:1:2] (0:5)' ] nnz(m) Lecture 2: Matlab basics - variables - question 4 Combining two matrices Initialise the random number generator with a seed of 5. Select the uniform distribution, and create a random number matrix of 5 rows by 5 columns. Then create a Toeplitz matrix: t = toeplitz(1:5)

Out of these two, create a 10 rows by 5 columns matrix with the transpose of the random matrix and toeplitz matrix. Calculate the sum of the elements in the first column. Note: In Matlab, use the default random generator (to be selected with 'RandStream.getDefaultStream'). There were 2 hints, of which you needed 3

Hint "Transposing a matrix" (2 points, not used) You can obtain the transpose of a matrix by using a quote '. Try help transpose in Matlab. Beware of side effects when transposing matrices with complex numbers!

Hint "Using variables in creating a matrix" (3 points, not used) You can use variables in entering a matrix

a = [c , d] a = [e ; f] Your answer

% c and d must have same number of rows % e and f must have same number of columns
16.7885

Give the sum of the elements in the first column


Answ er

Your answer was correct! Additional feedback Keep up the good work! The procedure is quite straightforward, in Matlab: RandStream.getGlobalStream.reset(5) r = rand(5, 5) t = toeplitz(1:5) m = [r' ; t] // the ' does the transpose sum(m(:,1)) // sum of column 1 On older versions of Matlab, substitute getDefaultStream for getGlobalStream Lecture 2: Matlab basics - variables - question 5 How can you determine the size of the variables in your workspace? Please select the most complete answer. The model answer Use the commands "ncols" to determine the number of columns and "nrows" to determine the number of rows of a matrix. Use the command "size(A)" to determine the size of matrix A. Either use the command "whos()" to get a list of all variables in the workspace, together with their sizes, or use "size(A)" to determine the size of a specific matrix.

Use the command "dir".


Answ er

Additional feedback This was multiple choice, supposed to be easy! You can use "whos()" and "size(A)" Lecture 2: Matlab basics - operations - question 1 Initialize the random number generator with a seed of 7. Then create a 5 rows by 5 columns matrix, using the normal distribution. Calculate the eigenvalues of the matrix, and determine which eigenvalue is biggest, and which is the smallest. Note that eigenvalues can be complex, consider the magnitude (norm) of the eigenvalue to determine its size! Note: In Matlab, use the default random generator (to be selected with 'RandStream.getGlobalStream', or 'RandStream.getDefaultStream' for older Matlab versions). There were 2 hints, of which you needed 20

Hint "What command to use?" (3 points, not used) In Matlab, eigenvalues are calculated with eig.

Hint "What is the largest eigenvalue?" (3 points, not used) To calculate the size of the elements of the vector with eigenvalues, use the command abs. Note that "large" in eigenvalue sense refers to the size of the complex vector.

The model answer Give the real part of the largest eigenvalue Give the real part of the smallest eigenvalue
Answ er
2.157228 -0.5673126

Additional feedback Come on, simple Matlab programming. You can do better! Answer: RandStream.getGlobalStream.reset(7) a = randn(5,5) e = eig(a) % calculate the norm of the complex numbers abs(e) Then select and enter the real parts of the largest and smallest eigenvalues.

Lecture 2: Matlab basics - operations - question 2 In classical control theory, complex numbers are often used. A complex number can be represented as the sum of a real number, and an imaginary number, z=a+bi. In an alternative representation complex numbers are represented by their magnitude and their angle. For this, the complex number is represented as a vector in the complex plane, with the length of the vector being the magnitude, and the angle between the positive real axis and the vector is the angle of the complex number. Given the same complex number, these are given as: Msin=b/Mcos=a/M=a2+b2 Please answer the following simple questions on these three complex numbers:

a = 6 + 3i b = -2 + -1i c = -4 + -5i

There were 2 hints, of which you needed 5

Hint "Careful with atan!" (2 points, not used) Consider the following figure:

The magnitude of a complex number can be calculated by multiplying it with its complex conjugate and taking the square root of the result. The angle of a complex number can be calculated by taking the arctangent of its imaginary part divided by its real part. Take care with this however, because the

angle of 4+4i is not equal to the angle of 44i, while simple calculation would produce 45 degrees for both! Check the documentation of atan for a clue on efficiently calculating the angles. In Matlab, use atan2.

Hint "And also with Matlab code" (4 points, not used) Use the 4-quadrant arctangent function version, so phi = atan2(imag(a), real(a)) always gives you the correct angle (note that it is still in radians!). For example -->a = - 1 - %i a = - 1. - i -->atan(imag(a)/ real(a)) // incorrect ans = 0.7853982 -->atan2(imag(a), real(a)) // correct ans = - 2.3561945

The model answer What is the angle of the complex number a, in degrees What is the angle of the complex number b, in degrees What is the magnitude of the complex number c
Answ er
26.565051 -153.43495 6.4031242

Additional feedback Correct angles are important! Consider the following figure:

To calculate the magnitude of a complex number, the magnitude of its vector representation must be determined. As an example, given a number a, the magnitude is calculated as follows:

>> a = 2+4i a = 2.0000 + 4.0000i >> sqrt(a .* conj(a)) ans = 4.4721 >> abs(a) % of course, abs also works ans = 4.4721 Note the use of the .*element-wise operator. In this way, the calculation also works when a is a vector or matrix. To get the angle of a, the 4 quadrant arctangent function must be used. Don't forget to convert the result to degrees, as asked in the question: >> phi=atan2(imag(a), real(a)) phi = 1.1071 Lecture 2: Matlab basics - operations - question 3 Create a matrix with one row with values that start at 0, with regular intervals of size 0.02 between the elements and end at 5. Calculate the sine of all elements in the matrix, and return the sum of those values. There were 2 hints, of which you needed 7

Hint "Generating a row vector" (4 points, not used) You can create a row vector with equally spaced intervals using the colon : operator. Try ``help colon''. Example: example = 0:0.15:20 Hint "More on which commands to use" (3 points, not used) Check help for sum and sine

Your answer Give the sum of all elements


Answ er
35.3362

Your answer was correct! Additional feedback Very good, a perfect score. With ``size'' set to the step size, the following one-liner should work: sum(sin(0:size:5)) Lecture 2: Matlab basics - operations - question 4 Initialize the random number generate with seed 4. Use the normal distribution, and create a 20 rows by 70 columns random matrix. Calculate the sum of all elements that are larger than 2.

Note: In Matlab, use the default random generator (to be selected with 'RandStream.getDefaultStream' or 'RandStream.getGlobalStream'). There were 2 hints, of which you needed 21

Hint "Testing and boolean matrices" (5 points, not used) You can use the bigger-than operator > to test the values in a matrix. For example: x > 3 Gives a boolean matrix (with true (T) and false (F)) values. Note that you can use this boolean matrix as an index, creating a vector with the value for all selected (true) indexes.

Hint "Using the result of such a test" (3 points, used) Check the result of: a(a > 2) Your answer

Give the sum of all elements larger than 2


Answ er

91.4448

The model answer Give the sum of all elements larger than 2
Answ er
91.444757

Additional feedback Come on, simple Matlab programming. You can do better! The following should work: RandStream.getDefaultStream.reset(4) a = randn(20, 70) sum(a(a > 2)) Lecture 2: Matlab basics - operations - question 5 The random generator in Matlab can generate both a uniform distribution and a normal (Gaussian) distribution. For the Gaussian distribution, it is known that 95.44997361036 % of the samples is within two standard deviations of the mean. Thus, for the Matlab random generator, which has a mean of 0 and a standard deviation of 1, theoretically 95.44997361036 % of the samples is larger than -2 and smaller than 2. Test this experimentally. Select the normal distribution in the random generator, initialize the random generator with a seed of 5, then create a random vector of 10000 elements. Note: In Matlab, use the default random generator (to be selected with 'RandStream.getDefaultStream' or 'RandStream.getGlobalStream'). There was one hint which you did not need

Hint "If you think you have to count this all by hand" (4 points, not used) You can use logical operators to obtain matrices with ``true'' and ``false'' values: a = rand(10,10) biga = a > 0.5

The Matlab function find returns indices of the true values, and with length you can check the size of this vector with indices. The model answer How many percent of the generated (pseudo) random values is between -2 and 2?
Answ er
95.43

Additional feedback Think Matlab, think matrices! % parameters of the problem seed = 5 % fill in your seed nelt = 10000 % fill in size of vector RandStream.getDefaultStream.reset(seed) v = randn(nelt, 1); n = length(find(v > -2 & v < 2)) n / nelt * 100

S-ar putea să vă placă și