How to randomise numbers in a vector?

14 views (last 30 days)
Bianca Elena Ivanof
Bianca Elena Ivanof on 17 Dec 2016
Edited: Jan on 19 Dec 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

Accepted Answer

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

Sign in to comment.

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 17 Dec 2016
Edited: Andrei Bobrov on 17 Dec 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 Comments
Jan
Jan on 18 Dec 2016
Edited: Jan on 18 Dec 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 on 18 Dec 2016
dear andrei,
thank you for your help.

Sign in to comment.

Categories

Find more on Colormaps in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!