How to randomise numbers in a vector?

9 visualizaciones (últimos 30 días)
Bianca Elena Ivanof
Bianca Elena Ivanof el 17 de Dic. de 2016
Editada: Jan el 19 de Dic. de 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

Respuesta aceptada

Jan
Jan el 17 de Dic. de 2016
Editada: Jan el 17 de Dic. de 2016
See doc randperm:
x = [1;2;3;4]
y = x(randperm(numel(x)))
If this is time-critical, use FEX: Shuffle .
  5 comentarios
Bianca Elena Ivanof
Bianca Elena Ivanof el 18 de Dic. de 2016
Editada: Bianca Elena Ivanof el 18 de Dic. de 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 el 19 de Dic. de 2016
Editada: Jan el 19 de Dic. de 2016
Y = reshape(X(:, 3), 4, [])
YS = Shuffle(Y, 1); % Mix columns
X(:, 3) = YS(:);

Iniciar sesión para comentar.

Más respuestas (1)

Andrei Bobrov
Andrei Bobrov el 17 de Dic. de 2016
Editada: Andrei Bobrov el 17 de Dic. de 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 comentarios
Jan
Jan el 18 de Dic. de 2016
Editada: Jan el 18 de Dic. de 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 el 18 de Dic. de 2016
dear andrei,
thank you for your help.

Iniciar sesión para comentar.

Categorías

Más información sobre Colormaps en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by