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.m71 chars5 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.m71 chars5 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