Randomly select an element

221 vues (au cours des 30 derniers jours)
Vero Alin
Vero Alin le 16 Nov 2017
Commenté : Vero Alin le 16 Nov 2017
Hello. I have an array: A=[4 8 7 9 5] How to I randomly select an element from the array? Thanks a lot.

Réponse acceptée

KL
KL le 16 Nov 2017
Modifié(e) : KL le 16 Nov 2017
  3 commentaires
KL
KL le 16 Nov 2017
Modifié(e) : KL le 16 Nov 2017
Yes, it is. The documentation says so. You could test it like,
A=[4 8 7 9 5];
A_rand = zeros(1,15);
for k = 1:numel(A_rand)
A_rand(1,k) = randsample(A,1);
end
now the result is,
A_rand =
5 5 5 4 9 8 7 5 9 8 4 7 5 7 4
Another alternative is to create the index randomly but that's pretty much the same,
A(randi([1 numel(A)],1)) or A(randperm(numel(A),1))
Vero Alin
Vero Alin le 16 Nov 2017
Alright. Thank you. Much appreciated.

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