How to Use Randn in MATLAB to Generate Random Numbers Within Certain Bounds
MATLAB is a technical software program which can perform arithmetic, calculus, linear algebra computations, figure plotting, signal processing and hundreds of other applications. Its versatility comes from its thousands of built-in, preprogrammed functions. One of those functions is “randn.” Tell the function how many rows and columns of data you desire, and it creates a matrix of random values that size, where the values fall into a “normal” or “bell curve” distribution around a mean. You cannot directly give “randn” minimum and maximum limits, but what you can do instead is stretch its output over whatever range you need.
Instructions
-
-
1
Create a matrix of random, normally distributed values using the randn function. For example, type at MATLAB’s command prompt:
A = randn(4, 5)
Hit Enter. MATLAB creates a matrix “A” with four rows and five columns. The matrix’s 20 values will be normally distributed around a central mean.
-
2
Calculate the difference between the maximum number in “A” and the minimum number in “A” with the following code:
FDiff = max(A) – min(A)
MATLAB stores the randn function’s range in “FDiff.” For example, if the minimum number was -0.1 and the maximum was 1.9, then MATLAB would give “FDiff” the value two.
-
-
3
Calculate the difference between the maximum and minimum numbers over which you want the random numbers stretched. For example, type this code and hit Enter:
RDiff = 30 - 10
MATLAB will store your desired range in “RDiff.” In this example, the maximum number in the range you want is 30, and the minimum is 10. MATLAB stores the value 20 in “RDiff.”
-
4
Calculate the scale you need in order to stretch the values in matrix “A” to fit them over your range. Type at the prompt and hit Enter:
scale = RDiff/FDiff
Using the previous example numbers, MATLAB divides 20 by two and gives “scale” the value 10.
-
5
Scale the values in matrix “A,” so they stretch as wide or as narrow as your desired range with the following code:
A2 = scale*A
-
6
Shift the matrix “A2” up or down the number line until its minimum value matches your minimum value, for example 10, with this code:
A3 = A2 + (10 – min(A2))
This final result, "A3," is a matrix of normally distributed numbers all within the range you set. In this example, those random numbers stretch from 10 to 30.
-
1