To generate random numbers in MATLAB, use rand for uniformly distributed numbers between 0 and 1, randn for normally distributed numbers, and randi for random integers within a specified range. For example, rand(3) creates a 3-by-3 matrix of uniform values, while randi([1, 100], 1, 5) returns five random integers from 1 to 100.
Why Random Numbers Matter in MATLAB
Random numbers are essential in simulations, statistical sampling, Monte Carlo methods, and randomized algorithms. MATLAB provides several functions to generate pseudo-random numbers, which are deterministic sequences that appear random. These functions are built on a well-tested random number generator (RNG) engine, ensuring reproducibility when you set a seed.
Core Random Number Functions
MATLAB offers four primary functions for generating random numbers:
rand– Uniform distribution in the interval (0,1).randn– Normal (Gaussian) distribution with mean 0 and standard deviation 1.randi– Uniformly distributed random integers.randperm– Random permutation of integers (useful for shuffling).
Each function accepts size arguments to create scalars, vectors, or matrices. For instance, rand(2,3) gives a 2-by-3 matrix, and randn(1,1000) gives a row vector of 1000 normal values.
How to Specify Range and Shape
For rand and randn, the output is always in the standard distribution; to change the range or parameters, you apply arithmetic. For example, to generate uniform random numbers between 5 and 15, use a + (b-a)*rand(...) where a=5 and b=15. For normal distribution with mean mu and standard deviation sigma, use mu + sigma*randn(...).
For randi, the first argument is the maximum value (or a two-element vector [min, max]), and the subsequent arguments define the output size. Example: randi(10, 2, 4) creates a 2-by-4 matrix of integers between 1 and 10.
Reproducibility with rng and Seeding
By default, MATLAB’s RNG is seeded based on the current time, so each session produces different sequences. To make results reproducible, use rng(seed) before generating numbers, where seed is a nonnegative integer. For example, rng(42); rand(1,5) always returns the same five numbers. You can also save and restore the RNG state with s = rng; ... rng(s);.
MATLAB uses the Mersenne Twister algorithm by default, which has a period of 2^19937-1. You can change the generator type with rng(seed, 'twister') or other options like 'simdTwister' or 'combRecursive', but the default is sufficient for most applications.
Generating Random Integers and Permutations
To get random integers, randi is the go-to. For example, to simulate rolling a six-sided die 10 times: rolls = randi(6, 1, 10). To generate a random permutation of numbers 1 through N, use randperm(N). For instance, randperm(5) might return [3 1 5 2 4]. This is useful for shuffling data or creating random orderings.
Common Pitfalls and How to Avoid Them
One common mistake is using rand when you need integers, or forgetting to set the seed for reproducibility. Another issue is that rand and randn generate values in the open interval (0,1) – they never return exactly 0 or 1. If you need a closed interval, you can use randi for integers or adjust the formula.
Also, be cautious with randi when specifying a range: the syntax randi([a, b]) includes both endpoints. If you accidentally use randi(b) thinking it gives values from 0 to b, you’ll get 1 to b instead.
Performance and Alternative Methods
For large-scale simulations, generating random numbers can be a bottleneck. MATLAB’s built-in functions are highly optimized, but you can improve performance by generating all numbers at once rather than in a loop. For example, instead of for i=1:1000, x(i)=rand(); end, use x = rand(1,1000);.
If you need random numbers from other distributions (e.g., exponential, Poisson), use the Statistics and Machine Learning Toolbox functions like exprnd, poissrnd, or random with a distribution name. Without the toolbox, you can apply transformations, such as -log(1-rand) for exponential.
Frequently Asked Questions
How do I generate a random number between 0 and 100?
Use 100*rand for a uniform double, or randi(101)-1 for an integer between 0 and 100 (since randi(101) gives 1 to 101).
Why do I get the same random numbers every time I start MATLAB?
That happens if you set a seed with rng in your startup script. To get different numbers each session, do not set a seed, or use rng('shuffle') to seed based on the current time.
Can I generate random numbers from a normal distribution with a specific mean and variance?
Yes. For mean mu and standard deviation sigma, use mu + sigma*randn(m,n). For example, 5 + 2*randn(1,100) gives 100 values with mean 5 and std 2.
What is the difference between rand and randn?rand gives values uniformly distributed between 0 and 1, so every value in that range is equally likely. randn gives values from a normal (bell-shaped) distribution, where values near 0 are more likely than extreme values.
How do I generate a random logical array (true/false)?
Use rand(n) > 0.5 for a 50% chance of true, or rand(n) < p for probability p. For example, rand(3) < 0.3 gives a 3-by-3 logical array with about 30% true values.
Is it possible to generate random numbers without the Statistics Toolbox?
Yes, for uniform and normal distributions, rand and randn are in base MATLAB. For other distributions, you can use inverse transform sampling or the random function if you have the toolbox, but base MATLAB alone covers the most common needs.
Related
- Google Sheets Personal Finance: Setup Guide
- Generate Random Number Range C++: A Practical Guide
- What Is the Shortcut for Save? (Ctrl+S & More)
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Tips and Shortcuts for Faster, Cleaner WorkbooksFor faster Excel work, learn a few reliable Windows shortcuts, turn data ranges into tables, and use formulas…
- Using Solver in Excel to Find Values That Sum to a TargetTo find which numbers add up to a target in Excel, assign each number a 0-or-1 decision cell,…
- How to Create a Heat Map in ExcelTo create a heat map in Excel for Microsoft 365 on Windows, select the numeric cells, then choose…
- Unmerge Excel Cells Without Losing DataTo unmerge cells in Excel for Microsoft 365 on Windows, select the merged cell or range, then choose…
- Excel Data Table Shortcut: What It Does and How to Use ItExcel has no single universal keyboard shortcut for the What-If Analysis Data Table command: in Windows, choose Data…
- Excel Slicer Examples for PivotTables and Tables ExplainedUseful Excel slicer examples include filtering a sales PivotTable by region, a product table by category, or a…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.