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

27 vues (au cours des 30 derniers jours)
Marvin
Marvin le 22 Mar 2012
Commenté : Andrew Sol le 13 Mar 2023
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.

Réponse acceptée

Wayne King
Wayne King le 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 commentaires
Marvin
Marvin le 22 Mar 2012
Thanks, I tried changing the seed and it didn't seem to work, the problem was that I was changing the seed at the beginning of the program, not inside the loop! Silly mistake. Thanks for all the help!
Aldin
Aldin le 22 Mar 2012
Congratulations

Connectez-vous pour commenter.

Plus de réponses (3)

Image Analyst
Image Analyst le 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);
  6 commentaires
Image Analyst
Image Analyst le 13 Mar 2023
@Andrew Sol Since they will not be there (infinitesimally small chance) if you're just getting random numbers, you will have to add them in manually: Somthing like:
% Generate values from the uniform distribution on the interval [a, b]:
a = 5;
b = 10;
numElements = 7;
r = a + (b-a).*rand(numElements,1);
% Add in the max and min
r = [a; b; r];
% Scramble the array so they are not at the beginning
scrambledIndexes = randperm(numel(r));
r = r(scrambledIndexes)
r = 9×1
7.1316 10.0000 9.8263 6.0645 6.5554 7.7677 7.3234 5.0000 5.1012
Andrew Sol
Andrew Sol le 13 Mar 2023
@Image Analyst Thank you very much for your answer! it's really not that complicated

Connectez-vous pour commenter.


Aldin
Aldin le 22 Mar 2012
It's very helpful.

Nisha Bharti
Nisha Bharti le 12 Jan 2022
To generate a random number between [a,b]:
r = a + (b-a)*rand();
To generate N numbers:
r = a + (b-a)*rand(1,N);

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by