How to create a set of random numbers

6 vues (au cours des 30 derniers jours)
Joy
Joy le 30 Mar 2017
Commenté : Joy le 31 Mar 2017
Hi, how I could generate random number 90 times
  1. probability space are 1, 2, 3
  2. totally 90 random numbers
  3. got 21 of 1, 38 of 2 and 31 of 3
Could you give me some solutions?
Thanks Joy

Réponse acceptée

Stephen23
Stephen23 le 30 Mar 2017
Modifié(e) : Stephen23 le 30 Mar 2017
You could use randperm to randomly arrange a vector of exactly those numbers:
>> vec = [repmat(1,21,1);repmat(2,38,1);repmat(3,31,1)]; % or use REPELEM
>> vec = vec(randperm(numel(vec)));
And checking that it fulfills your requirements:
>> numel(vec)
ans = 90
>> nnz(vec==1)
ans = 21
>> nnz(vec==2)
ans = 38
>> nnz(vec==3)
ans = 31
  1 commentaire
Joy
Joy le 31 Mar 2017
Thanks lot. It's much better than using a for loop.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Random Number Generation 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