MATLAB Answers

How do I create a single random number between two values?

275 views (last 30 days)
Marvin
Marvin on 22 Mar 2012
Commented: Kabeer Akande on 17 Sep 2015
I need to create a value for one of my variables in a loop which will run ten times. I need it to be between two set values, e.g. 1e3 and 9e3. Sorry for what is probably a very basic question but I am new to matlab.

Accepted Answer

Wayne King
Wayne King on 22 Mar 2012
Does it have to be an integer, or any number between 1e3 and 9e3?
For the former:
Int = randi([1e3 9e3],1,1);
For the latter:
R = 1e3+8e3*rand(1,1);
The preceding line gives you a uniform random number between 1e3 and 9e3.
  4 Comments

Sign in to comment.

More Answers (2)

Image Analyst
Image Analyst on 22 Mar 2012
The help facility is always a good place to start. If you had searched the help for rand, you would have seen the very first example:
Example 1
Generate values from the uniform distribution on the interval [a, b]:
r = a + (b-a).*rand(100,1);
  3 Comments
Image Analyst
Image Analyst on 22 Mar 2012
I agree that it might have been confusing since they didn't say what the 100 was right there in the example. You can send an email to support@mathworks.com if you find their documentation confusing. Perhaps they can change the wording to make it more clear. For example, tell them it should say "Generate 100 values from the uniform distribution on the interval [a, b]"

Sign in to comment.


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!