Inclusive random numbers on a matrix in matlab

2 vues (au cours des 30 derniers jours)
Laura Sofía Macías
Laura Sofía Macías le 30 Sep 2020
Hi I need to make a 20x10 matrix with random numbers between 0 and 5, inclusive. I already have the matrix but I can't manage to make it inclusive, all the numbers go up tu 4.9999, does anyone know how to do it? I used this formula M=0+(5-0).*rand(20,10)

Réponse acceptée

Ameer Hamza
Ameer Hamza le 30 Sep 2020
Modifié(e) : Ameer Hamza le 30 Sep 2020
20x10 matrix is too small. rand() generates uniformly distributed random number, and the probability of getting exactly one is significantly less. If you increase the number of the element, you will have a good chance of getting one in rand()
For example
>> M=0+(5-0).*rand(2000,1000); % 2000x1000
>> max(M, [], 'all')
ans =
5.0000
Checking at higher precision, even this value is less than 5
>> format long
>> max(M, [], 'all')
ans =
4.999999540115017
Getting excatly 5 is "almost impossible".
If you really want 0 as lower and 5 as upper limit, then you will need to use rescale()
>> M=0+(5-0).*rand(2000,1000); % 2000x1000
>> M = rescale(M, 0, 5);
>> max(M, [], 'all')
ans =
5
>> min(M, [], 'all')
ans =
0
  3 commentaires
Ameer Hamza
Ameer Hamza le 30 Sep 2020
I am glad to be of help!
Andrew M. Soltisz
Andrew M. Soltisz le 23 Mai 2024
Technically, MATLAB's rand() function does not include 0 and 1 (i.e. its range is not inclusive of 0 and 1). So it is literally impossible to randomly sample these numbers from the uniform distribution using MATLAB's built-in function. However, Python's Numpy random.random() method can sample in the range of [0.0, 1.0), so it is inclusive to 0, so there are methods out there to provide inclusive sampling.

Connectez-vous pour commenter.

Plus de réponses (0)

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