random number between x<=y in matlab

To generate a random number in matlab between two values x and y, you can use the function rand which generates a random number from a uniform distribution between 0 and 1. You can then scale and shift this random number to fit your desired range [x, y].

Here's an example code snippet that generates a random number between 5 and 10:

main.m
x = 5;
y = 10;
r = (y-x)*rand + x;
disp(r) % display the random number
71 chars
5 lines

In this code, (y-x)*rand generates a random number between 0 and y-x, and adding x shifts this range to start from x.

Note that this method generates a random number from a continuous uniform distribution (i.e., any number in the range [x, y] is equally likely). If you want to generate a random integer between x and y, you can use the randi function instead:

main.m
x = 5;
y = 10;
r = randi([x, y]);
disp(r) % display the random integer
71 chars
5 lines

In this code, randi([x, y]) generates a random integer from a uniform distribution over the integers between x and y (inclusive).

gistlibby LogSnag