random number between x and y in matlab

To generate a random number between a range x and y in MATLAB, you can use the rand function to generate a random number from a uniform distribution and then scale it to the desired range using some basic algebra:

main.m
x = 10;  % minimum value of range
y = 20;  % maximum value of range
r = x + (y-x)*rand;  % generate random number between x and y
130 chars
4 lines

In this code, rand generates a random number between 0 and 1 from a uniform distribution. The expression (y-x)*rand scales the random number to be within the desired range, and the x + part shifts it to the right place.

You can easily generate multiple random numbers at once by specifying the size of the output array as an argument to rand, and then scaling and shifting the result array as needed:

main.m
x = 10;  % minimum value of range
y = 20;  % maximum value of range
n = 5;   % number of random numbers to generate
r = x + (y-x)*rand(1,n);  % generate n random numbers between x and y
186 chars
5 lines

gistlibby LogSnag