Skip to main content

Section 3.5 Examples and questions

These are additional examples for reviewing the topic we have covered. When reading each example, try to find your own solution before clicking “Answer”. There are also questions for reviewing the concepts of this section.

Given numbers \(a, b\) with \(a \lt b\text{,}\) construct a random 5×5 matrix in which the entries are uniformly distributed between \(a\) and \(b\text{.}\)

Answer
A = (b-a)*rand(5, 5) + a;

Explanation: we take random numbers between 0 and 1, and then apply a linear function which sends 0 to a, and 1 to b. This function is \(y = (b-a)x + a\text{.}\)

The functions mean and median are aggregate functions which work similarly to sum. For example, mean([1 9 8 3]) is 5.25 which is \((1+9+8+3)/4\text{.}\) And median([1 9 8 3]) is 5.5 because when these numbers are sorted as 1, 3, 8, 9 there are two in the middle, and their average is \((3+8)/2 = 5.5\text{.}\) (When the number of data values is odd, the median is the number in the middle.)

Plot a histogram of the mean of 10 random numbers, with 10000 such means computed.

Answer
A = rand(10, 10000); 
m = mean(A, 1);
histogram(m, 30)

Explanation. Having created a random matrix A, we take the mean of each column with mean(A, 1). If we used median(A, 1) the result would be a similar histogram.

For 10 randomly chosen numbers (with rand) we can compute both mean and median. How different can these be? That is, how large can the difference |mean-median| be? Try to approach this experimentally by computing this difference 10000 times and taking the maximum.
Answer
A = rand(10, 10000); 
m = mean(A, 1);
md = median(A, 1);
disp(max(abs(m-md)))

The result of computation depends on your luck. There is no guarantee that the maximum found after 10000 random tries is close to the actual maximum.

Suppose v is a vector with 10 elements, in which 6 elements are 0 and the others are 1. What are the mean and the median of v? (You should not need a computer for this.) Is the difference between the mean and the median in this example greater than what you found experimentally in Example 3.5.3?

We know that x = rand() produces a random number between 0 and 1. The command x = rand()^2 also produces a random number between 0 and 1. Is there a significant difference between these two ways of creating random numbers?