How to Use randn in MATLAB: Syntax and Examples
In MATLAB, use
randn to generate random numbers from a standard normal distribution (mean 0, variance 1). You can specify the size of the output matrix by passing dimensions as arguments, like randn(3,4) for a 3-by-4 matrix of random values.Syntax
The randn function generates random numbers from a normal distribution with mean 0 and standard deviation 1.
r = randn: Returns a single random number.r = randn(n): Returns ann-by-nmatrix.r = randn(m,n): Returns anm-by-nmatrix.r = randn(sz): Returns an array with size specified by vectorsz.
matlab
r = randn; r = randn(3); r = randn(2,4); r = randn([2,3,4]);
Output
r = 0.5377
r =
-1.2075 0.2773 1.0845
0.2779 0.5469 -0.5643
-0.5469 -0.4634 0.2410
r =
0.5377 -1.2075 0.2773 1.0845
0.2779 0.5469 -0.5643 -0.5469
r = randn array of size 2x3x4 with random values
Example
This example creates a 3-by-3 matrix of random numbers from the standard normal distribution and calculates its mean and standard deviation.
matlab
A = randn(3,3); meanA = mean(A, 'all'); stdA = std(A, 0, 'all'); [A, meanA, stdA]
Output
[
-0.8147 0.9058 0.1270
0.9134 0.6324 0.0975
0.2785 0.5469 0.9575
]
meanA = 0.2204
stdA = 0.5837
Common Pitfalls
Common mistakes when using randn include:
- Confusing
randnwithrand.randngenerates normal distribution values,randgenerates uniform distribution values. - Not specifying size arguments correctly, which can cause unexpected output shapes.
- Assuming
randnoutput is always positive; it can be negative since it is normally distributed.
matlab
wrong = randn; right = randn(1,1);
Output
wrong = 0.5377
right = 0.5377
Quick Reference
| Usage | Description |
|---|---|
| randn | Single random number from standard normal distribution |
| randn(n) | n-by-n matrix of random numbers |
| randn(m,n) | m-by-n matrix of random numbers |
| randn(sz) | Array with size specified by vector sz |
Key Takeaways
Use randn to generate random numbers from a normal distribution with mean 0 and variance 1.
Specify dimensions as arguments to control the size of the output matrix or array.
randn can produce negative and positive values because it follows a normal distribution.
Do not confuse randn with rand; rand generates uniform random numbers.
Use mean and std functions to analyze the generated random data.