How to randomise numbers in a vector?

24 vues (au cours des 30 derniers jours)
Bianca Elena Ivanof
Bianca Elena Ivanof le 17 Déc 2016
Modifié(e) : Jan le 19 Déc 2016
Dear all,
Suppose I have this vector x= [1;2;3;4];
How can I randomise it? (i.e. create different combinations of 1, 2, 3 and 4)
Thank you very much in advance, Bianca

Réponse acceptée

Jan
Jan le 17 Déc 2016
Modifié(e) : Jan le 17 Déc 2016
See doc randperm:
x = [1;2;3;4]
y = x(randperm(numel(x)))
If this is time-critical, use FEX: Shuffle .
  5 commentaires
Bianca Elena Ivanof
Bianca Elena Ivanof le 18 Déc 2016
Modifié(e) : Bianca Elena Ivanof le 18 Déc 2016
Dear Jan,
Thank you very much for your help. The second option works wonders! I am trying to randomise the subconditions of the main conditions of my experiment - in order for me to do so, there is one last step I need to figure out. I understand if this post is becoming a bit too lengthy for you but, if not, could you please be so kind as to help me understand one more thing? If yes, please see the file attached.
counterbalancing(:,1)= participant ID
counterbalancing(:,2)= speed levels (1, 2, 3)
counterbalancing(:,3)= conditions (1, 2, 3, 4) per speed level
What I am trying to do is, for every speed level (column 2) per participant (column 1), to randomise the 4 speed level subconditions (column 3) - i.e. to randomise the first 4 rows containing 1, 2, 3, 4 and then the next 4 rows containing 1, 2, 3, 4 and so on and so forth, until the end of the matrix. I very vaguely remember there is a simple of doing computations on every n rows at a time, which doesn't require for loops or anything of the sort.
Jan
Jan le 19 Déc 2016
Modifié(e) : Jan le 19 Déc 2016
Y = reshape(X(:, 3), 4, [])
YS = Shuffle(Y, 1); % Mix columns
X(:, 3) = YS(:);

Connectez-vous pour commenter.

Plus de réponses (1)

Andrei Bobrov
Andrei Bobrov le 17 Déc 2016
Modifié(e) : Andrei Bobrov le 17 Déc 2016
Hi Elena!
One way:
x= [1 1; 1 2; 1 3; 1 4]
[~,ii] = sort(rand(size(x,1),1));
out = x(ii,:);
or just
out = x(randperm(size(x,1)),:);
  2 commentaires
Jan
Jan le 18 Déc 2016
Modifié(e) : Jan le 18 Déc 2016
randperm uses the Fisher-Yates shuffle now (as FEX: Shuffle), which is more accurate than SORT(RAND). The later is a stable sort, so if two elements replied by RAND are equal (unlikely, but not impossible) the sorting order is not random. If you e.g. have to shuffle a vector of 2^52 elements, uuhm, well... Who cares.
Bianca Elena Ivanof
Bianca Elena Ivanof le 18 Déc 2016
dear andrei,
thank you for your help.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Colormaps 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